BFS 版本的匈牙利算法

#include<iostream>
#include<vector>
#include<unordered_set>
#include<queue>
#include<stack>
#include<cstring>
#include<queue>

using namespace std;

int hungry_bfs(vector<vector<int> >& bi_graph, int m, vector<int>& match) {
    int n = bi_graph.size();
    match.clear();
    match.resize(m, -1);
    int ret = 0;
    for (int i = 0; i < n; ++i) {
        unordered_set<int> visited;   //记录访问过的右节点
        vector<int> match_tmp(n, -1); //试探性匹配:l->r
        queue<int> Q;                 //试探顺序控制队列
        Q.push(i);
        stack<int> S;                 //记录试探性匹配的左节点的顺序
        bool ext = false;
        while (!Q.empty() && !ext) {
            int c = Q.front();
            Q.pop();
            for (int adj : bi_graph[c]) {
                if (visited.count(adj) != 0) continue;
                if (match[adj] == -1) {
                    //构造增广链
                     match_tmp[c] = adj;
                     S.push(c);
                     while (!S.empty()) {
                         int cc = S.top();
                         S.pop();
                         match[match_tmp[cc]] = cc;
                     }
                     match_tmp.clear();
                     ext = true;
                     break;
                } else {
                    visited.insert(adj);
                    Q.push(match[adj]);
                    match_tmp[c] = adj;
                    S.push(c);
                }
            }
            if (ext) {
                ret += 1;
            }
        }
    }
    return ret;
}


int main() {
    int n, m;
    cin>>n>>m;
    int ne;
    cin>>ne;
    vector<vector<int> > bi_graph(n, vector<int>());
    for (int i = 0; i < ne; ++i) {
        int l, r;
        cin>>l>>r;
        bi_graph[l].push_back(r);
    }
    vector<int> match;
    int ret = hungry_bfs(bi_graph, m, match);
    cout<<ret<<endl;
    return 0;
}
点赞