题目:
思路一:网络流:
增加超源超,构建网络求解最大流即可!
思路二:匈牙利求最大匹配:
将每头牛与其喜爱的牛棚都连接一条容量为1的边,用匈牙利算法,求最大匹配。
一共V个顶点,边集为E,时间复杂度为:O(VE);
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e2 + 10, M = N*N;
int h[N], ne[M], e[M], idx;
int n, m;
int match[N];
bool st[N];
void add (int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool find(int u)
{
for (int i=h[u]; ~i; i = ne[i])
{
int j = e[i];
if (!st[j])
{
st[j] = true;
if (!match[j] || find(match[j]))
{
match[j] = u;
return true;
}
}
}
return false;
}
int main()
{
while (~scanf ("%d%d", &n, &m))
{
memset(h, -1, sizeof h);
memset (match, 0, sizeof (match));
for (int i=1; i <= n; i ++)
{
int k;
scanf("%d", &k);
while (k --)
{
int x;
scanf ("%d", &x);
add (i, x);
}
}
int res=0;
for (int i=1; i <= n; i++)
{
memset(st, 0, sizeof st);
if (find(i)) res ++;
}
printf ("%d\n", res);
}
return 0;
}