题意
有N个项目需要解决,其中会遇到M个技术问题。
完成每个项目会获得正收益,解决一个技术问题需要付出代价。完成一个项目之前需要先解决与之相关的技术问题。解决一个技术问题x之前,可能需要先解决技术问题y。如果x和y相互依赖,则同时解决。
解题
将项目看作X部,技术问题看作Y部。
X部与Y部的依赖,则连有向弧(x,y)。
Y部内部yi对yj的依赖(先解决yi,才能解决yj),则连有向弧(yi,yj)。
容量都为无穷大。
然后按照解决最大权闭合子图的方法去建网络图即可。
从源点到X部连一条容量为收益的有向弧;
从Y部连一条容量为代价的有向弧。
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <string>
#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()
{
int kase=0,t;
scanf("%d",&t);
while(t--)
{
init();
int n,m,sum=0;
scanf("%d%d",&n,&m);
S=0,T=n+m+1;
for(int i=1;i<=n;i++)
{
int c;
scanf("%d",&c);
_add(S,i,c);
sum+=c;
}
for(int i=1;i<=m;i++)
{
int c;
scanf("%d",&c);
_add(i+n,T,c);
}
for(int i=1;i<=n;i++)
{
int k;
scanf("%d",&k);
while(k--)
{
int x;
scanf("%d",&x);
_add(i,x+1+n,INF);
}
}
for(int i=1;i<=m;i++)
for(int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
if(x) _add(i+n,j+n,INF);
}
int ans=Dinic();
printf("Case #%d: ",++kase);
printf("%d\n",sum-ans);
}
return 0;
}