861. 二分图的最大匹配

不设置st出现无限递归的原因:
对于一个x号男生来说,找他的邻接点j,若j已经心有所属,那么会find(match[j]),
会让编号为match[j]的男生重新去找,那么这个男生开始找,如果在他已经匹配到的女生之前没有找到空闲的女生,
或者无法通过find()换一个另外的女生,那么这个男生找到的仍然是自己原来匹配的女生,此时match[j]!=0,
所以会执行find(match[j]), 此时无限递归了。。。
设置st的目的:保证本次匹配过程中,第二个集合中的每个点只被遍历一次,防止死循环

#include<iostream>
#include<cstring>

using namespace std;

const int N = 510, M = 100010;

int n1, n2;
int m;
int h[N], e[M], ne[M], idx;
int match[N], st[N];

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; i = ne[i]){
        int j = e[i];
        if(st[j] == 0){
            st[j] = 1;
            if(match[j] == 0 || find(match[j])){
                match[j] = x;
                return 1;
            }
        }
    }
    return 0;
}

int main(){
    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;
    return 0;
}
原文地址:https://www.cnblogs.com/tomori/p/13622632.html