Cod sursa(job #875121)

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

using namespace std;

typedef vector<int>::iterator it;

const int MaxN = 20005;
const int NIL = -1;

vector<int> G[MaxN];
int N, M, Pair[MaxN], Side[MaxN], Father[MaxN], MaxMatching;;

int PairUp(const int Start) {
    queue<int> Q;
    Father[Start] = Start;
    for (Q.push(Start); !Q.empty(); Q.pop()) {
        int X = Q.front();
        if (Pair[X] == NIL && X != Start) {
            for (; X != Start; X = Father[Father[X]])
                Pair[X] = Father[X], Pair[Father[X]] = X;
            return 1;
        }
        if (Side[X] == 0) {
            int Y = Pair[X];
            if (Father[Y] == NIL && (Side[X] ^ Side[Y] == 1))
                Q.push(Y), Father[Y] = X;
        } else {
            for (it Y = G[X].begin(); Y != G[X].end(); ++Y)
                if (Father[*Y] == NIL && (Side[X] ^ Side[*Y] == 1))
                    Q.push(*Y), Father[*Y] = X;
        }
    }
    return 0;
}

void MaximumMatching() {
    memset(Pair, NIL, sizeof(Pair));
    for (int Change = 1; Change != 0; ) {
        memset(Father, NIL, sizeof(Father));
        Change = 0;
        for (int X = 1; X <= N; ++X)
            if (Father[X] == NIL && Pair[X] == NIL)
                Change |= PairUp(X);
    }
    for (int X = 1; X <= N; ++X)
        MaxMatching += (Pair[X] != NIL);
}

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(N + Y), G[N + Y].push_back(X);
    }
    for (int X = 1; X <= N; ++X)
        Side[X] = 1;
}

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

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