网络流之二分图匹配(POJ-1274 The Perfect Stall)

Description

Farmer John completed his new barn just last week, complete with all the latest milking technology. Unfortunately, due to engineering problems, all the stalls in the new barn are different. For the first week, Farmer John randomly assigned cows to stalls, but it quickly became clear that any given cow was only willing to produce milk in certain stalls. For the last week, Farmer John has been collecting data on which cows are willing to produce milk in which stalls. A stall may be only assigned to one cow, and, of course, a cow may be only assigned to one stall.
Given the preferences of the cows, compute the maximum number of milk-producing assignments of cows to stalls that is possible.
Input

The input includes several cases. For each case, the first line contains two integers, N (0 <= N <= 200) and M (0 <= M <= 200). N is the number of cows that Farmer John has and M is the number of stalls in the new barn. Each of the following N lines corresponds to a single cow. The first integer (Si) on the line is the number of stalls that the cow is willing to produce milk in (0 <= Si <= M). The subsequent Si integers on that line are the stalls in which that cow is willing to produce milk. The stall numbers will be integers in the range (1…M), and no stall will be listed twice for a given cow.
Output

For each case, output a single line with a single integer, the maximum number of milk-producing stall assignments that can be made.

输入:
5 5
2 2 5
3 2 3 4
2 1 5
3 1 2 5
1 2 
输出:
4

思路
二分图匹配的一个模板题

AC代码:

#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
const int INF=0x7fffffff;
const int maxn=500+5;
int n,m;
int vis[maxn],liu[maxn][maxn],p[maxn];
int EK_BFS(int start,int end)
{
	queue<int>q;//不用全局 ,省去清空队列的麻烦 
	memset(vis,0,sizeof(vis));
	memset(p,-1,sizeof(p));
	q.push(start);
	vis[start]=1;
	while(q.size()){
		int t=q.front();
		q.pop();
		if(t==end)
			return 1;//到达汇点 
		for(int i=0;i<=n+m+1;i++){//寻找增广路径 
			if(liu[t][i]!=0&&!vis[i]){ //存在这样的路径并且没有走过 
				vis[i]=1;
				p[i]=t;//记录增广路径 
				q.push(i);
			}
		}
	}
	return 0;//残留图中不再存在增广路径 
}
int EK_network(int start,int end)
{
	int ans=0;
	while(EK_BFS(start,end)){
		int u=end;//利用前驱寻找路径 
		int temp=INF;
		while(p[u]!=-1){
			temp=min(temp,liu[p[u]][u]);
			u=p[u];
		}
		u=end;
		ans+=temp;
		while(p[u]!=-1){
			liu[p[u]][u]-=temp;//改变正向边的容量 
			liu[u][p[u]]+=temp;//反向边,防止出现堵塞的情况
							   //改变反向边的容量 
			u=p[u]; 
		}
	}
	return ans;
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF){
		memset(liu,0,sizeof(liu));
		for(int i=1;i<=n;i++){
			int x,y;
			scanf("%d",&x);
			while(x--){
				scanf("%d",&y);
				liu[0][i]=1;
				liu[i][n+y]=1;	
				liu[n+y][n+m+1]=1;
			}
		}
		printf("%d\n",EK_network(0,n+m+1));
	}
	return 0;
}
发布了40 篇原创文章 · 获赞 6 · 访问量 1402

猜你喜欢

转载自blog.csdn.net/qq_43321732/article/details/104181925
今日推荐