Cod sursa(job #2596658)

Utilizator CharacterMeCharacter Me CharacterMe Data 10 aprilie 2020 10:14:39
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

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

int n, m, e, cnt, sol;
vector<int> graph[10005];
int toLft[10005], toRgt[10005];

bool tryCouple(int node);

int main()
{

    fin >> n >> m >> e;

    while(e--){
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }

    do{
        cnt = 0;

        for(int i = 1; i <= n; ++i) {
            if(!toRgt[i]){
                if(tryCouple(i)) ++cnt;
            }
        }

    }while(cnt);

    for(int i = 1; i <= n; ++i){
        if(toRgt[i]) ++sol;
    }

    fout << sol << "\n";

    for(int i = 1; i <= n; ++i){
        if(toRgt[i]){
            fout << i << " " << toRgt[i] << "\n";
        }
    }

    return 0;
}

bool tryCouple(int node){
    int avoid = toRgt[node];

    for(auto next:graph[node]){
        if(next != avoid && !toLft[next]){
            toLft[next] = node;
            toRgt[node] = next;
            return true;
        }
    }

    for(auto next:graph[node]){
        if(next != avoid){
            if(tryCouple(toLft[next])){
                toLft[next] = node;
                toRgt[node] = next;
                return true;
            }
        }
    }

    return false;
}