Cod sursa(job #1404170)

Utilizator SmarandaMaria Pandele Smaranda Data 27 martie 2015 20:54:19
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

const int N = 20003;

bool used [N];
int n, m;
int a [N], b [N];
vector <int> graph [N];

int cuplaj (int x) {
    bool flag;
    vector <int> :: iterator it;

    if (used [x] == 1)
        return 0;

    used [x] = 1;
    for (it = graph [x].begin (); it != graph [x].end (); ++ it)
        if (!b [*it]) {
            a [x] = *it;
            b [*it] = x;
            return 1;
        }
    for (it = graph [x].begin (); it != graph [x].end (); ++ it)
        if (b [*it] && b [*it] != x) {
            flag = cuplaj (b [*it]);
            if (flag == 1) {
                b [*it] = x;
                a [x] = *it;
                return 1;
            }
        }
    return 0;
}

int main () {
    int i, j, e, x, y, ans = 0;
    bool flag;

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

    scanf ("%d%d%d", &n, &m, &e);
    for (i = 1; i <= e; i ++) {
        scanf ("%d%d", &x, &y);
        y = n + y;
        graph [x].push_back (y);
    }
    flag = true;
    while (flag) {
        flag = 0;
        memset (used, 0, sizeof (used));
        for (i = 1; i <= n; i ++) {
            if (a [i] == 0) {
                if (cuplaj (i)) {
                    ans ++;
                    flag = 1;
                }
            }
        }
    }
    printf ("%d\n", ans);
    for (i = 1; i <= n; i ++)
        if (a [i])
            printf ("%d %d\n", i, a [i] - n);
    return 0;
}