Cod sursa(job #2172419)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 15 martie 2018 16:25:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 2e4 + 10;

int n, m, e, cnt;
int _pair[nmax];
bool used[nmax];
vector < int > g[nmax];

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

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

    return 0;
}

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

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

    ios_base :: sync_with_stdio(false);

    cin >> n >> m >> e;
    for (int i = 1; i <= e; ++i) {
        int x, y;
        cin >> x >> y; y += n;

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

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

    cout << cnt << '\n';
    for (int i = 1; i <= n; ++i)
        if (_pair[i])
            cout << i << ' ' << _pair[i] - n << '\n';

    return 0;
}