Cod sursa(job #2655314)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 3 octombrie 2020 22:58:32
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 20005, inf = 1e9;
int n, m, e, dist[nmax], match[nmax];
vector <int> G[nmax];

bool bfs(){
    queue <int> coada;
    for (int i = 1; i <= n; ++i){
        if (!match[i]){
            coada.push(i);
            dist[i] = 0;
        }
        else{
            dist[i] = inf;
        }
    }
    dist[0] = inf;
    while (!coada.empty()){
        int nod = coada.front();
        coada.pop();
        if (nod != 0){
            for (auto it : G[nod]){
                if (dist[match[it]] == inf){
                    dist[match[it]] = 1 + dist[nod];
                    coada.push(match[it]);
                }
            }
        }
    }
    return dist[0] != inf;
}

bool dfs(int nod){
    if (nod != 0){
        for (auto it : G[nod]){
            if (dist[match[it]] == 1 + dist[nod]){
                if (dfs(match[it])){
                    match[nod] = it;
                    match[it] = nod;
                    return true;
                }
            }
        }
        return false;
    }
    return true;
}

int hopcroft_karp(){
    int cuplaj = 0;
    while (bfs()){
        for (int i = 1; i <= n; ++i){
            if (!match[i] && dfs(i)){
                ++cuplaj;
            }
        }
    }
    return cuplaj;
}

int main(){
    fin >> n >> m >> e;
    for (int i = 1; i <= e; ++i){
        int x, y;
        fin >> x >> y;
        G[x].push_back(y + n);
        G[y + n].push_back(x);
    }
    fout << hopcroft_karp() << "\n";
    for (int i = 1; i <= n; ++i){
        if (match[i]){
            fout << i << " " << match[i] - n << "\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}