1. 程式人生 > 實用技巧 >匈牙利演算法(二分圖的最大匹配)

匈牙利演算法(二分圖的最大匹配)

#include <bits/stdc++.h>
using namespace std;

const int N = 550, M = 100010;
int h[N], e[M], ne[M], idx;
int match[N];
bool st[N];
int n1, n2, m;

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int find(int x) {
    for(int i = h[x]; i != -1; i = ne[i]) {
        int
j = e[i]; if(!st[j]) { st[j] = true; // 注意這裡 已標記為true 在find(match[j]) 中找match[j]的其他可匹配物件時,j已被標記為訪問,不會再訪問j if(!match[j] || find(match[j])) { match[j] = x; return true; } } } return false; } int main() { scanf(
"%d%d%d",&n1,&n2,&m); memset(h,-1,sizeof h); while(m -- ) { int a, b; scanf("%d%d",&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; }