Cod sursa(job #1968308)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 17 aprilie 2017 16:53:31
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 1e5 + 10;

int n, m, edges;

int used[nmax], p[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 pair_up(int node) {
    if (used[node]) return 0;

    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 (pair_up(p[it])) {
            p[node] = it; p[it] = node;
            return 1;
        }

    return 0;
}

void maxmatch() {
    while (true) {
        bool nxt = 0;
        memset(used, 0, sizeof(used));

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

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

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

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

    input();
    maxmatch();
    output();

    return 0;
}

/*void min_vertex_cover(int node) {
    for (auto &it: g[node])
        if (!s[it]) {
            s[it] = 1; s[p[it]] = 0;
            min_vertex_cover(p[it]);
        }
}

void run_mvc() {
    for (int i = 1; i <= n; ++i)
        s[i] = (p[i] != 0);
    for (int i = 1; i <= n; ++i)
        if (!s[i]) min_vertex_cover(i);
}*/