poj 1274

题目链接:poj 1274


二分图匹配

正好学了网络流,本想着用网络流来搞一搞,结果,一直 WA  

改了一下数组大小。。竟然 A 了,Orz

想不明白(还是去学一下匈牙利吧 T_T

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 200000;
const int INF = 10000000;
struct Node{
	int to;
	int ne;
	int w;
}e[N<<1];
int head[N],deth[N];
int n,m,x,y,st,en,val,cnt;
void init()
{
	memset(head,-1,sizeof(head));
	cnt = st = 0;
	en = n + m + 1;
}
void add(int u,int v,int val)
{
	e[cnt].to = v;
	e[cnt].ne = head[u];
	e[cnt].w = val;
	head[u] = cnt ++;
}
int bfs()
{
	memset(deth,0,sizeof(deth));
	queue<int>q;
	deth[st] = 1;
	q.push(st);
	while(!q.empty())
	{
		int now = q.front();
		q.pop();
		for(int i=head[now];~i;i=e[i].ne)
		{
			int to = e[i].to;
			if(deth[to] == 0 && e[i].w > 0)
			{
				deth[to] = deth[now] + 1;
				q.push(to);
			}
		}
	}
	if(deth[en] == 0)
		return 0;
	return 1;
} 
int dfs(int u,int dist)
{
	if(u == en)
	return dist;
	int temp = dist;
	for(int i=head[u];~i;i = e[i].ne)
	{
		int to = e[i].to;
		if(deth[to] == deth[u] + 1 && e[i].w > 0)
		{
			int di = dfs(to,min(e[i].w,temp));
			if(di>0)
			{
				temp -= di;
				e[i].w -= di;
				e[i^1].w += di;
				if(temp <= 0)
				return dist;
			}
		}
	}
	return dist - temp;
}
int dinic()
{
	int ans = 0;
	while(bfs())
	{
		while(int di = dfs(st,INF))
		{
			ans += di;
		}
	}
	return ans;
}
int main()
{
	while(scanf("%d%d",&n,&m) != EOF)
	{
		init();
		for(int i=1;i<=n;i++)
		{
			add(st,i,1);
			add(i,st,0);
		}
		for(int i=1;i<=m;i++)
		{
			add(en,i+n,0);
			add(i+n,en,1);
		}
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&x);
			for(int j = 1;j <= x;j ++)
			{
				scanf("%d",&y);
				add(i,y+n,1);
				add(y+n,i,0);
			}
		}
		printf("%d\n",dinic());
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lizhiwei2017/article/details/80113209