这是一个二分图匹配的模板题
直接贴代码吧
#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;
}
本文提供了一个二分图匹配问题的完整代码实现,通过构建增广路径来寻找最大匹配,适用于解决各种二分图匹配问题。
3506

被折叠的 条评论
为什么被折叠?



