假设n1
是男生数量,n2
是女生数量,匈牙利算法求二分图的最大匹配数,即求男生与女生最大匹配数
题目思路
match[b] = a
,女生b
匹配的男生是a
st[i]
,i
在本轮遍历中是否已匹配
- 遍历每个男生,让每个男生去find一个女生。
find(x)
,以x
为端点寻找所有邻接边,即可以匹配的女生;若j
是本轮还没有匹配过的,继续判断是否match[j] == 0
(女生j
是否一直没有被匹配过)或find(match[j])
(即女生j
已经被匹配过了,递归去让j
已经匹配过的男生match[j]
,重新去找下一个女生),若其中一个成功(女生未匹配过男生,或女生匹配的男生能找到下一个女生),令match[j] = x
,该男生匹配此女生成功。- 在每次遍历男生的时候,都需要
memset(st, false, sizeof st)
,重置一次状态。
C++代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 510, M = 100010;
int n1, n2, m;
int h[N], e[M], ne[M], idx;
int match[N];
int st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx, idx++;
}
bool find(int x)
{
for (int i = h[x]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
st[j] = true;
if (match[j] == 0 || find(match[j]))
{
match[j] = x;
return true;
}
}
}
return false;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
memset(h, -1, sizeof h);
cin >> n1 >> n2 >> m;
while (m--)
{
int a, b;
cin >> a >> b;
add(a, b);
}
int res = 0;
for (int i = 1; i <= n1; i++)
{
memset(st, false, sizeof st);
if (find(i))
{
res++;
}
}
cout << res;
return 0;
}