Cod sursa(job #2587872)

Utilizator RazvanPanaiteRazvan Panaite RazvanPanaite Data 23 martie 2020 17:51:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>
#define pb push_back

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

void debug_out() { cerr << '\n'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"

typedef pair<int,int> pii;
typedef long long int ll;
typedef long double ld;

const int DMAX = 1e5+10;

class Cuplaj{
    private:
        int m, n;
        vector <vector<int>> V;
        vector <int> st, dr;
        vector <bool> uz;

    bool cup(int node) {
        if (uz[node])
            return 0;
        uz[node] = true;
        for(auto& it: V[node])
            if(!dr[it]){
                st[node]=it;
                dr[it]=node;
                return 1;
            }
        for(auto& it: V[node])
            if(cup(dr[it])){
                st[node]=it;
                dr[it]=node;
                return 1;
            }
        return 0;
    }

    public:
        Cuplaj(int n, int m) {
            this->n=n;
            this->m=m;
            V.resize(n+1);
            st.resize(n+1);
            dr.resize(m+1);
            uz.resize(n+1);
        }

        void addEdge(int x, int y) {
            V[x].push_back(y);
        }

        void match() {
            bool ok;
            do {
                ok = false;
                for(int i = 1; i <= n; i++)
                    uz[i]=false;
                for(int i = 1; i <= n; i++)
                    if(!st[i] && !uz[i])
                        if(cup(i))
                            ok=true;
            } while (ok);

            int ans = 0;
            for(int i = 1; i <= n; i++)
                ans += (bool) st[i];
            fout<<ans<<'\n';
            for(int i = 1;i <= n; i++)
                if(st[i])
                    fout<<i<<' '<<st[i]<<'\n';
        }
};

int n,m,e;

int main(){
    int t,i,j;
    int x,y;

    fin>>n>>m>>e;
    Cuplaj cup(n,m);
    while(e--){
        fin>>x>>y;
        cup.addEdge(x,y);
    }
    cup.match();

    return 0;
}