匈牙利算法(二分图的最大匹配) -2025/11/6
匈牙利算法(二分图的最大匹配)
#include<bits/stdc++.h>
using namespace std;
const int N = 510, M = 100010;
int h[N], e[M], ne[M], idx;
int n1 , n2 ,m;
int match[N];
int st[N];
void add(int a,int b){
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
bool find(int u){
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(!st[j]){
st[j] = 1;
if(!match[j] || find(match[j])){
match[j] = u;
return true;
}
}
}
return false;
}
int main(){
ios::sync_with_stdio(false), cin.tie(0);
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, 0 , sizeof st);
if(find(i)) res++;
}
cout << res << "\n";
return 0;
}

浙公网安备 33010602011771号