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

   

#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;
}
原文地址:https://www.cnblogs.com/yonezu/p/13498581.html