Cod sursa(job #1811560)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 21 noiembrie 2016 12:34:51
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 2e4 + 10;

int n, m, edges;
int cuplat[nmax];
vector < int > g[nmax];

bool used[nmax];

void input() {
    scanf("%d %d %d", &n, &m, &edges);
    for (int i = 1; i <= edges; ++i) {
        int x, y;
        scanf("%d %d", &x, &y);

        g[x].push_back(y+n);
        g[y+n].push_back(x);
    }
}

bool pair_up(int node) {
    used[node] = 1;
    for (auto &it : g[node])
        if (!cuplat[it]) {
            cuplat[node] = it; cuplat[it] = node;
            return 1;
        }

    for (auto &it : g[node])
        if (!used[cuplat[it]] && pair_up(cuplat[it])) {
            cuplat[node] = it; cuplat[it] = node;
            return 1;
        }

    return 0;
}

void solve() {
    while (true) {
        for (int j = 1; j <= n; ++j)
            used[j] = 0;

        bool ok = 0;
        for (int i = 1; i <= n; ++i) {
            if (cuplat[i] || used[i]) continue;
            ok |= pair_up(i);
        }

        if (!ok) break;
    }
}

void output() {
    int ans = 0;
    for (int i = 1; i <= n; ++i)
        if (cuplat[i]) ans++;

    printf("%d\n", ans);
    for (int i = 1; i <= n; ++i)
        if (cuplat[i]) printf("%d %d\n", i, cuplat[i] - n);
}

int main()
{
    freopen("cuplaj.in","r",stdin);
    freopen("cuplaj.out","w",stdout);

    input();
    solve();
    output();

    return 0;
}