Cod sursa(job #2695508)

Utilizator MevasAlexandru Vasilescu Mevas Data 13 ianuarie 2021 15:23:43
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <bitset>
#include <vector>

using namespace std;

constexpr int Nmax = 10010;

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

vector<int> v[Nmax];
int n, m, k, dr[Nmax], st[Nmax];
bitset<Nmax> visited;

bool cuplaj(const int x) {
    if(visited[x]) {
        return false;
    }
    visited[x] = true;
    for(const auto y : v[x]) {
        if(!st[y]) {
            dr[x] = y;
            st[y] = x;
            return true;
        }
    }
    for(const auto y : v[x]) {
        if(cuplaj(st[y])) {
            dr[x] = y;
            st[y] = x;
            return true;
        }
    }
    return false;
}

void mk_cuplaj() {
    bool notDone = true;
    while(notDone) {
        visited = 0;
        notDone = false;
        for(int i = 1; i <= n; ++i)
            if(!dr[i])
                notDone = (cuplaj(i) || notDone);
    }
}

int main() {
    fin >> n >> m >> k;
    for(int i = 0, x, y; i < k; ++i) {
        fin >> x >> y;
        v[x].push_back(y);
    }

    mk_cuplaj();

    fout << Nmax - count(dr, dr + Nmax, 0) << endl;
    for(int i = 1; i <= n; ++i) {
        if(dr[i]) {
            fout << i << ' ' << dr[i] << '\n';
        }
    }
}