[AcWing 861] 二分图的最大匹配


点击查看代码
#include<iostream>
#include<cstring>
using namespace std;
const int N = 510, M = 1e5 + 10;
int n1, n2, m;
int h[N], e[M], ne[M], idx;
bool st[N];
int match[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = 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 >> n1 >> n2 >> m;
memset(h, -1, sizeof h);
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 << endl;
return 0;
}
- 匈牙利算法思路:对左半部中的每个点,找到右半部中匹配的点,能匹配成功的右半部的点需要满足以下条件:
① 没被访问过;(对左半部中的每个点,都会先把 st 都置为 false)
② 没有和左半部中其他的点匹配,或者已经匹配的左半部的那个点可以和右半部的另一个点匹配;

浙公网安备 33010602011771号