Cod sursa(job #3259819)

Utilizator alexdumitruAlexandru Dumitru alexdumitru Data 27 noiembrie 2024 21:40:25
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

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

const int MAX_N = 10000;
const int MAX_M = 10000;

int n, m, k;
std::vector<int> g[MAX_N + 1];
bool vis[MAX_N + 1];
int l[MAX_N + 1];
int r[MAX_M + 1];

void read() {
    fin >> n >> m >> k;
    for (int i = 0; i < k; i++) {
        int u, v;
        fin >> u >> v;
        g[u].push_back(v);
    }
}

bool pair_up(int node) {
    if (vis[node])
        return false;
    vis[node] = true;
    for (int to : g[node])
        if (!r[to]) {
            l[node] = to;
            r[to] = node;
            return true;
        }
    for (int to : g[node])
        if (pair_up(r[to])) {
            l[node] = to;
            r[to] = node;
        }
    return false;
}

void solve() {

    bool ok = true;
    while (ok) {
        ok = false;

        for (int i = 1; i <= n; i++)
            vis[i] = false;

        for (int i = 1; i <= n; i++)
            if (!l[i])
                ok |= pair_up(i);
    }

    int cnt = 0;

    for (int i = 1; i <= n; i++)
        if (l[i])
            cnt++;

    fout << cnt << '\n';

    for (int i = 1; i <= n; i++)
        if (l[i])
            fout << i << ' ' << l[i] << '\n';
}

int main() {
    read();
    solve();
    return 0;
}