Cod sursa(job #1736151)

Utilizator andreea_zahariaAndreea Zaharia andreea_zaharia Data 1 august 2016 12:24:03
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>
#include <vector>

using namespace std;

#define NMAX 10005

vector<int> G[NMAX];

int NL, NR, M;

int L[NMAX], R[NMAX], used[NMAX];

bool pairUp (int N) {
    if (used[N]) {
        return 0;
    }

    used[N] = 1;

    for (int i = 0; i < G[N].size(); i++) {
        if ( !R[G[N][i]]) {
            L[N] = G[N][i];
            R[G[N][i]] = N;
            return 1;
        }
    }

    for (int i = 0; i < G[N].size(); i++) {
        if (pairUp(R[G[N][i]])) {
            L[N] = G[N][i];
            R[G[N][i]] = N;
            return 1;
        }
    }
    return 0;
}

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

    scanf ("%d%d%d", &NL, &NR, &M);

    while (M--) {
        int x, y;
        scanf ("%d%d", &x, &y);
        G[x].push_back (y);

    }

    int modif = 1;
    while (modif) {
        modif = 0;

        for (int i = 0; i <= NL + 1; used[i] = 0, i++);

        for (int i = 1; i <= NL; i++) {
            if ( !L[i] && pairUp (i)) {
                modif = 1;
            }
        }
    }

    int cuplajMax = 0;
    for (int i = 1; i <= NL; i++) {
        if (L[i] > 0) {
            cuplajMax++;
        }
    }
    printf ("%d\n", cuplajMax);

    for (int i = 1; i <= NL; i++) {
        if (L[i] > 0) {
            printf ("%d %d\n", i, L[i]);
        }
    }

    return 0;
}