最大匹配
匈牙利算法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 100010;
int h[N], e[M], ne[M], idx;
int n1, n2, m;
bool st[N];
int res;
int match[N];
void add(int a, int b) { // 添加一条边a->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] == 0 || find(match[j])) {
match[j] = u;
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);
}
for (int i = 1; i <= n1; i++) {
memset(st, 0, sizeof st);
if (find(i))res++;
}
cout << res;
return 0;
}

浙公网安备 33010602011771号