Cod sursa(job #2716902)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 5 martie 2021 21:30:54
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
//
// Created by mihai145 on 05.03.2021.
//

#include <fstream>
#include <vector>

using namespace std;

ifstream cin("cuplaj.in");
ofstream cout("cuplaj.out");

const int NMAX = 1e4;

int N, M, E;
vector<int> g[NMAX + 2];

int matching;
int l[NMAX + 2], r[NMAX + 2];
bool d[NMAX + 2];

bool PairUp(int node) {
    if(d[node]) {
        return false;
    }

    d[node] = true;

    for(int it : g[node]) {
        if(!r[it]) {
            ++matching;
            r[it] = node;
            l[node] = it;
            return true;
        }
    }

    for(int it : g[node]) {
        if(PairUp(r[it])) {
            r[it] = node;
            l[node] = it;
            return true;
        }
    }

    return false;
}

int main() {
    cin >> N >> M >> E;

    for(int i = 1; i <= E; i++) {
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
    }

    bool ok = false;
    do {
        ok = false;

        for(int i = 1; i <= N; i++) {
            d[i] = false;
        }

        for(int i = 1; i <= N; i++) {
            if(!l[i]) {
                ok |= PairUp(i);
            }
        }
    } while (ok);

    cout << matching << '\n';
    for(int i = 1; i <= N; i++) {
        if(l[i]) {
            cout << i << ' ' << l[i] << '\n';
        }
    }

    return 0;
}