Cod sursa(job #875122)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 9 februarie 2013 18:48:21
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <cstdio>
#include <cassert>
#include <vector>

using namespace std;

typedef vector<int>::iterator it;

const int MaxN = 10005;

vector<int> G[MaxN];
int N, M, L[MaxN], R[MaxN], MaxMatching;;
bool Used[MaxN];

int PairUp(const int X) {
    if (Used[X])
        return 0;
    Used[X] = true;
    for (it Y = G[X].begin(); Y != G[X].end(); ++Y) {
        if (L[*Y] == 0) {
            R[X] = *Y, L[*Y] = X;
            return 1;
        }
    }
    for (it Y = G[X].begin(); Y != G[X].end(); ++Y) {
        if (PairUp(L[*Y])) {
            R[X] = *Y, L[*Y] = X;
            return 1;
        }
    }
    return 0;
}

void MaximumMatching() {
    for (int Change = 1; Change != 0; ) {
        Change = 0;
        for (int X = 1; X <= N; ++X)
            Used[X] = false;
        for (int X = 1; X <= N; ++X)
            if (R[X] == 0)
                Change |= PairUp(X);
    }
    for (int X = 1; X <= N; ++X)
        MaxMatching += (R[X] != 0);
}

void Read() {
    assert(freopen("cuplaj.in", "r", stdin));
    int E; assert(scanf("%d %d %d", &N, &M, &E) == 3);
    for (; E > 0; --E) {
        int X, Y; assert(scanf("%d %d", &X, &Y) == 2);
        G[X].push_back(Y);
    }
}

void Print() {
    assert(freopen("cuplaj.out", "w", stdout));
    printf("%d\n", MaxMatching);
    for (int X = 1; X <= N; ++X)
        if (R[X] != 0)
            printf("%d %d\n", X, R[X]);
}

int main() {
    Read();
    MaximumMatching();
    Print();
    return 0;
}