模板 - 二分图(匈牙利算法)

二分图(匈牙利算法)

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

using namespace std;
const int MAXN = 510;

int line[MAXN][MAXN];
int used[MAXN]; //在男生的某次访问里,女生能不能匹配到
int nxt[MAXN];  //如果匹配到的话,这个男生是谁

int n,m;

bool Find(int x) {
    for (int i = 1;i <= m;i ++){ //现在看是否有女生愿意匹配男生
        if (line[x][i] && !used[i]){ //这两个人相互喜欢,并且名花无主
            used[i] = 1;
            if (nxt[i] == 0 || Find(nxt[i])){ //如果这个女生没有匹配到人,或者她匹配的男生可以腾位置的
                 //为当前男生创建了一个空间
                 nxt[i] = x;
                 return true;
            }
        }
    }
    return false;
}

//我们一个男生一个男生去遍历,看他能不能被匹配到
int match() {
    int sum = 0;
    for (int i = 1;i <= n;i ++){
        memset(used,0,sizeof(used));
        if (Find(i)) sum ++;
    }
    return sum;
}

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int T;
    while (cin >> T,T){
        cin >> n >> m;
        memset(line,0,sizeof(line));
        memset(nxt,0,sizeof(nxt));

        int x,y;
        for (int i = 1;i <= T;i ++){
            cin >> x >> y;
            line[x][y] = 1;
        }
        cout << match() << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41428565/article/details/80435455