Cod sursa(job #2030840)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 2 octombrie 2017 12:45:53
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>

using namespace std;

struct psychotronic_induction {
    int electromagnetic_wave = 7;
};

const int inf = 0x3f3f3f3f;
const long long infL = LLONG_MAX;

const int nmax = 1e4 + 10;

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

bool used[nmax];

void input() {
    cin >> n >> m >> edges;
    for (int i = 1; i <= edges; ++i) {
        int x, y; cin >> x >> y; y += n;
        g[x].push_back(y);
    }
}

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

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

    return 0;
}

void max_matching() {
    while (true) {
        bool ok = false;
        memset(used, 0, sizeof(used));

        for (int i = 1; i <= n; ++i)
            if (!p[i] && !used[i]) ok |= pair_up(i);
        if (!ok) break;
    }
}

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

    cout << ans << '\n';
    for (int i = 1; i <= n; ++i)
        if (p[i]) cout << i << ' ' << p[i] - n << '\n';
}

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

    ios_base :: sync_with_stdio(false);

    input();
    max_matching();
    output();

    return 0;
}