题解
- 匈牙利算法:求一个二分图的最大匹配数,O(nm),实际远小于这个时间复杂度,,遵循“先到先得,能让则让”的原则
2. 模拟过程:1匹配最先的6,2匹配最先的7,3只有一个能匹配的6,但是6已经让1匹配,我们就需要看6所匹配的点1能否去匹配别的点,发现1除了能匹配6,还可以匹配8,所以就让1匹配8,3匹配6,4匹配7
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n1, n2, m;
int h[N], e[N], ne[N], idx;
int match[N];
bool st[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() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
memset(h, -1, sizeof h);
cin >> n1 >> n2 >> m;
for (int i = 1; i <= m; i++) {
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;
}