Cod sursa(job #882815)

Utilizator sebii_cSebastian Claici sebii_c Data 19 februarie 2013 15:04:43
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

const int MAXN = 10001;

bool vis[MAXN];
int l[MAXN];
int r[MAXN];

vector<int> G[MAXN];

int pair_up(int node)
{
    if (vis[node])
        return 0;
    vis[node] = true;

    vector<int>::iterator it;
    for (it = G[node].begin(); it != G[node].end(); ++it) {
        if (!r[*it]) {
            l[node] = *it;
            r[*it] = node;
            return 1;
        }
    }
    for (it = G[node].begin(); it != G[node].end(); ++it) {
        if (pair_up(r[*it])) {
            l[node] = *it;
            r[*it] = node;
            return 1;
        }
    }
    return 0;
}

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

    int n, m, e;
    scanf("%d %d %d", &n, &m, &e);
    for (int i = 0; i < e; ++i) {
        int x, y;
        scanf("%d %d", &x, &y);
        G[x].push_back(y);
    }

    int coupling = 0;
    for (int i = 1; i <= n; ++i) {
        if (!l[i]) {
            memset(vis, false, sizeof(vis));
            coupling += pair_up(i);
        } else {
            coupling++;
        }
    }

    printf("%d\n", coupling);
    for (int i = 1; i <= n; ++i) 
        if (l[i] != 0)
            printf("%d %d\n", i, l[i]);

    return 0;
}