【最大流】【Dinic】bzoj1711 [Usaco2007 Open]Dingin吃饭
把牛拆点,互相连1的边。
把牛的食物向牛连边,把牛向牛的饮料连边。
把源点向牛的食物连边,把牛的饮料向汇点连边。
要把牛放在中间,否则会造成一头牛吃了自己的食物后又去喝别的牛的饮料的情况。
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; #define INF 2147483647 #define MAXN 411 #define MAXM 50301 int v[MAXM],cap[MAXM],en,first[MAXN],next[MAXM]; int d[MAXN],cur[MAXN]; queue<int>q; int n,S,T,n1,n2,n3,m1,m2,x; void Init_Dinic() {memset(first,-1,sizeof(first)); en=0; n=(n1<<1)+n2+n3; T=n+1; S=0;} void AddEdge(const int &U,const int &V,const int &W) {v[en]=V; cap[en]=W; next[en]=first[U]; first[U]=en++; v[en]=U; next[en]=first[V]; first[V]=en++;} bool bfs() { memset(d,-1,sizeof(d)); q.push(S); d[S]=0; while(!q.empty()) { int U=q.front(); q.pop(); for(int i=first[U];i!=-1;i=next[i]) if(d[v[i]]==-1 && cap[i]) { d[v[i]]=d[U]+1; q.push(v[i]); } } return d[T]!=-1; } int dfs(int U,int a) { if(U==T || !a) return a; int Flow=0,f; for(int &i=cur[U];i!=-1;i=next[i]) if(d[U]+1==d[v[i]] && (f=dfs(v[i],min(a,cap[i])))) { cap[i]-=f; cap[i^1]+=f; Flow+=f; a-=f; if(!a) break; } if(!Flow) d[U]=-1; return Flow; } int max_flow() { int Flow=0,tmp=0; while(bfs()) { memcpy(cur,first,(n+5)*sizeof(int)); while(tmp=dfs(S,INF)) Flow+=tmp; } return Flow; } int main() { scanf("%d%d%d",&n1,&n2,&n3); Init_Dinic(); for(int i=1;i<=n1;++i) { scanf("%d%d",&m1,&m2); for(int j=1;j<=m1;++j) { scanf("%d",&x); AddEdge(x,i+n2,1); } for(int j=1;j<=m2;++j) { scanf("%d",&x); AddEdge(i+n1+n2,x+(n1<<1)+n2,1); } } for(int i=1;i<=n2;++i) AddEdge(S,i,1); for(int i=1;i<=n3;++i) AddEdge(i+(n1<<1)+n2,T,1); for(int i=1;i<=n1;++i) AddEdge(i+n2,i+n1+n2,1); printf("%d\n",max_flow()); return 0; }
——The Solution By AutSky_JadeK From UESTC
转载请注明出处:http://www.cnblogs.com/autsky-jadek/