Cod sursa(job #2746695)

Utilizator YouDontNeedMyNameJurcut Paul YouDontNeedMyName Data 28 aprilie 2021 12:18:16
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

class Kuhn{
public:
    Kuhn(int n, int m){
        left.resize(m);
        right.resize(n);
        viz.resize(n);
        adj.resize(n);
    }
    void add_edge(int src, int dest){
        adj[src].push_back(dest);
    }
    bool fnd_match(int u){
        if(viz[u]) return false;
        viz[u] = true;
        for(auto v: adj[u]){
            if(!left[v] || fnd_match(left[v])){
                left[v] = u;
                right[u] = v;
                return true;
            }
        }
        return false;
    }
    vector<pair<int,int > > match(){
        bool ok = true;
        while(ok){
            ok = false;
            fill(viz.begin(), viz.end(), false);
            for(long unsigned int i=0; i<right.size(); i++){
                if(!right[i]){
                    ok|=fnd_match(i);
                }
            }
        }
        vector<pair<int,int > > sol;
        for(long unsigned int i=0; i<right.size(); i++){
            if(right[i]){
                sol.push_back({i, right[i]});
            }
        }
        return sol;
    }

    vector<bool> viz;
    vector<vector<int> > adj;
    vector<int> left;
    vector<int> right;
};

int main(){
    ifstream in("cuplaj.in");
    ofstream out("cuplaj.out");
    int n,m,e;
    in >> n >> m >> e;
    Kuhn graph(n+1,m+1);
    for(int i=0; i<e; i++){
        int x,y;
        in >> x >> y;
        graph.add_edge(x,y);
    }
    auto sol = graph.match();
    out << sol.size() << '\n';
    for(auto matched: sol){
        out << matched.first << " " << matched.second << '\n';
    }
    in.close();
    out.close();
    return 0;
}