Cod sursa(job #1906721)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 6 martie 2017 15:59:40
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 2e4 + 10;

int n, m, edges;
int _pair[nmax], used[nmax];
vector < int > g[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(n+y);
        g[n+y].push_back(x);
    }
}

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

    return 0;
}

void run_maxmatch() {
    for (bool ok = 1; ok; ) {
        memset(used, 0, sizeof(used)); ok = 0;
        for (int i = 1; i <= n; ++i)
            if (!_pair[i]) ok |= pairUp(i);
    }
}

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

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

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

    input();
    run_maxmatch();
    output();

    return 0;
}