题意
给n头牛和m个牛棚,一头牛只能在特定的牛棚产奶,一个牛棚只能同时容纳一头牛。求最大产奶数的牛和牛棚匹配方案。
思路
二分图匹配的模板题
题目链接
http://poj.org/problem?id=1274
AC代码
#include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
const int maxn = 200 + 10;
int n, m;
vector<int> G[maxn * 2];//存图
int match[maxn * 2];//存匹配
bool usd[maxn * 2];//一次dfs中的访问标记
//添加边
void Add(int a, int b)
{
G[a].push_back(b);
G[b].push_back(a);
}
//dfs找增广路
bool dfs(int v)
{
usd[v] = true;
for(int i= 0; i< G[v].size(); i++)
{
int u = G[v][i], w = match[u];
if(w < 0 || !usd[w] && dfs(w))
{
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
//最大匹配
int max_match()
{
int res = 0;
memset(match, -1, sizeof match);
for(int v= 0; v< n; v++)
if(match[v] < 0)
{
memset(usd, false, sizeof usd);
if(dfs(v)) res ++;
}
return res;
}
int main ()
{
while(scanf("%d %d", &n, &m) != EOF)
{
for(int i= 0; i<= n+m; i++)
G[i].clear();
for(int i= 0; i< n; i++)
{
int s;
scanf("%d", &s);
while(s--)
{
int t;
scanf("%d", &t);
Add(i, n+t);//添加边
}
}
cout << max_match() << endl;
}
return 0;
}