有n头牛与m个牛棚,给出每头牛愿意去产奶的牛棚编号,每头牛只可产一次奶,每个牛棚也只允许一只牛产奶。
二分匹配,模板题,匈牙利算法。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
int mp[210][210];
bool ck[210],v[210];
int p[210];
int n,m;
int find(int x)
{
int i,t;
for (i=1; i<=m; i++)
{
if (mp[x][i] == 1 && p[i] == 0)
{
p[i]=x;
return 1;
}
else if (mp[x][i] == 1 && p[i] != 0)
{
if (ck[i] == true || v[i] == true)
{
continue;
}
v[i]=true;
t=find(p[i]);
if (t == 1)
{
p[i]=x;
return 1;
}
else
{
ck[i]=true;
}
}
}
return 0;
}
int main()
{
int t1,t2,i,j,t,ans;
while (scanf("%d%d",&n,&m) != EOF)
{
memset(mp,0,sizeof(mp));
memset(ck,false,sizeof(ck));
memset(p,0,sizeof(p));
for (i=1; i<=n; i++)
{
scanf("%d",&t1);
for (j=0; j<t1; j++)
{
scanf("%d",&t2);
mp[i][t2]=1;
}
}
ans=0;
for (i=1; i<=n; i++)
{
memset(v,false,sizeof(v));
ans+=find(i);
}
printf("%d\n",ans);
}
}