标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 22539 | Accepted: 10072 |
Description
Input
Output
Sample Input
5 5 2 2 5 3 2 3 4 2 1 5 3 1 2 5 1 2
Sample Output
4
题意:农夫养了n头牛,建了m个牲口棚,他发现每头牛只在特定的一些牲口棚才能产奶,问最多有多少头牛能够同时产奶??
题解:二分图的最大匹配,设立一个超级源点,向每头牛连一条长度为1的单向边,建立超级汇点,每个牲口棚向超级汇点连一条长度为1的单向边,然后每头牛向其喜爱的牲口棚连一条长度不小于1的边,求最大流即可。
#include <stdio.h> #include <algorithm> #include <queue> #include <string.h> #include <math.h> #include <iostream> using namespace std; const int N = 505; const int INF = 999999999; struct Edge{ int v,w,next; }edge[N*N]; int head[N]; int level[N]; int tot; void init(){ memset(head,-1,sizeof(head)); tot=0; } void addEdge(int u,int v,int w,int &k){ edge[k].v = v,edge[k].w=w,edge[k].next=head[u],head[u]=k++; edge[k].v = u,edge[k].w=0,edge[k].next=head[v],head[v]=k++; } int BFS(int src,int des){ queue<int >q; memset(level,0,sizeof(level)); level[src]=1; q.push(src); while(!q.empty()){ int u = q.front(); q.pop(); if(u==des) return 1; for(int k = head[u];k!=-1;k=edge[k].next){ int v = edge[k].v,w=edge[k].w; if(level[v]==0&&w!=0){ level[v]=level[u]+1; q.push(v); } } } return -1; } int dfs(int u,int des,int increaseRoad){ if(u==des) return increaseRoad; int ret=0; for(int k=head[u];k!=-1;k=edge[k].next){ int v = edge[k].v,w=edge[k].w; if(level[v]==level[u]+1&&w!=0){ int MIN = min(increaseRoad-ret,w); w = dfs(v,des,MIN); edge[k].w -=w; edge[k^1].w+=w; ret+=w; if(ret==increaseRoad) return ret; } } return ret; } int Dinic(int src,int des){ int ans = 0; while(BFS(src,des)!=-1) ans+=dfs(src,des,INF); return ans; } int main(){ int n,m; while(scanf("%d%d",&n,&m)!=EOF){ init(); int src = 0,des = n+m+1; for(int i=1;i<=n;i++){ addEdge(src,i,1,tot); int t,v; scanf("%d",&t); while(t--){ scanf("%d",&v); addEdge(i,v+n,1,tot); } } for(int i=n+1;i<=n+m;i++){ addEdge(i,des,1,tot); } printf("%d\n",Dinic(src,des)); } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5551874.html