题意:
有n个奶牛m个谷仓,农场主John发现有的奶牛只喜欢在它喜欢的谷仓产奶,根据一周发现得出的数据,你需要计算最大匹配的数目
具体匈牙利算法还是要去看这个帅哥的。http://blog.csdn.net/dark_scope/article/details/8880547,写的非常非常赞,反倒是书上说的太复杂而想复杂看不懂了。具体过程去这个博主看吧。
本题正是采用匈牙利算法加链式前向星随意水过。
下面贴代码:
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<queue>
#include<cmath>
#include<fstream>
using namespace std;
//FILE *buf = freopen("t.txt", "a+", stdin);
const int MAX = 5000;//这里要注意开大点,200个点,最稠密都有4万条边
struct Edge
{
int next, to, v;
}edge[MAX << 1];
int head[MAX];
int k;
int cx[MAX], cy[MAX];
int bmark[MAX];
int N, M;
void addedge(int u,int v)
{
edge[k].to = v;
edge[k].next = head[u];
head[u] = k;
k++;
}
void init()
{
k = 0;
for (int i = 0; i < MAX; i++)
{
cx[i] = cy[i] = -1;
head[i] = -1;
}
head[0] = edge[0].next = -1;
}
bool findxy(int u)
{
for (int i = head[u]; i != -1; i = edge[i].next)
{
int to = edge[i].to;
if (!bmark[to])
{
bmark[to] = true;
if (cy[to] == -1 || findxy(cy[to]))
{
cy[to] = u;
cx[u] = to;
return 1;
}
}
}
return 0;
}
int Max_Match()
{
int MaxNum = 0;
for (int i = 1; i <= N; i++)
{
memset(bmark, false, sizeof(bmark));
if (findxy(i))
{
MaxNum++;
}
}
return MaxNum;
}
int main()
{
while (cin >> N >> M)
{
init();
for (int i = 1; i <= N; i++)
{
int a;
cin >> a;
while (a--)
{
int b;
cin >> b;
addedge(i, b);
}
}
cout << Max_Match() << endl;
}
return 0;
}