题意
一共有n块宝石,获取一块宝石会获得价值v,并需要花费代价v。要想获得宝石u必须先获得在u上面的宝石。
解题
题目描述符合闭合图的定义——图中选一个子图使得子图中点连出边的终点还在子图中。
所以这题就是求最大权闭合子图。
设一个源点S,汇点T。
从S到点权值为正的结点引入一条有向弧,容量为点权值。
从点权值为负的结点到T引入一条有向弧,容量为点权值的绝对值。
原图结点与结点的有向弧保留,容量为正无穷大。
跑一遍dinic算法求出最大流。
用与源点相连的边的容量和减去最大流即为所求。
AC代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
#define INF 0x3f3f3f3f
using namespace std;
int S,T;//源点和汇点
const int maxe=1e5+1000;
const int maxv=1100;
struct edge
{
int to,w,next;
}e[maxe<<1];
int head[maxv<<1],depth[maxv],cnt;
void init()
{
memset(head,-1,sizeof(head));
cnt=-1;
}
void add_edge(int u,int v,int w)
{
e[++cnt].to=v;
e[cnt].w=w;
e[cnt].next=head[u];
head[u]=cnt;
}
void _add(int u,int v,int w)
{
add_edge(u,v,w);
add_edge(v,u,0);
}
bool bfs()
{
queue<int> q;
while(!q.empty()) q.pop();
memset(depth,0,sizeof(depth));
depth[S]=1;
q.push(S);
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i!=-1;i=e[i].next)
{
if(!depth[e[i].to] && e[i].w>0)
{
depth[e[i].to]=depth[u]+1;
q.push(e[i].to);
}
}
}
if(!depth[T]) return false;
return true;
}
int dfs(int u,int flow)
{
if(u==T) return flow;
int ret=0;
for(int i=head[u];i!=-1 && flow;i=e[i].next)
{
if(depth[u]+1==depth[e[i].to] && e[i].w!=0)
{
int tmp=dfs(e[i].to,min(e[i].w,flow));
if(tmp>0)
{
flow-=tmp;
ret+=tmp;
e[i].w-=tmp;
e[i^1].w+=tmp;
}
}
}
return ret;
}
int Dinic()
{
int ans=0;
while(bfs())
{
ans+=dfs(S,INF);
}
return ans;
}
int main()
{
init();
int n,sum=0;
scanf("%d",&n);
S=0,T=n+1;
for(int i=1;i<=n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
int c=x-y;
if(c>0) _add(S,i,c),sum+=c;
else _add(i,T,-c);
int m;
scanf("%d",&m);
while(m--)
{
int v;
scanf("%d",&v);
_add(v,i,INF);
}
}
printf("%d\n",sum-Dinic());
return 0;
}