POJ1274: The Perfect Stall 题解

本文提供了一个二分图匹配问题的完整代码实现,通过构建增广路径来寻找最大匹配,适用于解决各种二分图匹配问题。

这是一个二分图匹配的模板题

直接贴代码吧

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;

const int MOD=1e9+7;
const int INF=0x7ffffff;
const int magic=348;

int depth[100048];
queue<int> q;
int t,tot,head[100048],nxt[200048],to[200048],f[200048];
inline void addedge(int s,int t,int cap)
{
	to[++tot]=t;nxt[tot]=head[s];head[s]=tot;f[tot]=cap;
	to[++tot]=s;nxt[tot]=head[t];head[t]=tot;f[tot]=0;
}

int n,m;

bool bfs()
{
	int i,x,y;
	for (i=0;i<=t;i++) depth[i]=-1;
	depth[0]=0;
	q.push(0);
	while (!q.empty())
	{
		x=q.front();q.pop();
		for (i=head[x];i;i=nxt[i])
		{
			y=to[i];
			if (f[i] && depth[y]==-1)
			{
				depth[y]=depth[x]+1;
				q.push(y);
			}
		}
	}
	if (depth[t]==-1) return false; else return true;
}

int dfs(int x,int maxf)
{
	if (x==t) return maxf;
	int i,y,now,minf,ans=0;
	for (i=head[x];i;i=nxt[i])
	{
		y=to[i];
		if (f[i] && depth[y]==depth[x]+1)
		{
			minf=min(maxf-ans,f[i]);
			now=dfs(y,minf);
			f[i]-=now;
			f[i^1]+=now;
			ans+=now;
		}
	}
	return ans;
}

int main ()
{
	int i,j,x,ax;
	while (scanf("%d%d",&n,&m)!=EOF)
	{
		t=n+m+1;
		tot=1;
		for (i=0;i<=t;i++) head[i]=0;
		for (i=1;i<=n;i++) addedge(0,i,1);
		for (i=1;i<=m;i++) addedge(n+i,t,1);
		for (i=1;i<=n;i++)
		{
			scanf("%d",&ax);
			for (j=1;j<=ax;j++)
			{
				scanf("%d",&x);
				addedge(i,n+x,1);
			}
		}
		int ans=0;
		while (bfs()) ans+=dfs(0,2e9);
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值