Cod sursa(job #1947798)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 31 martie 2017 13:05:23
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
/**
  *  Worg
  */
#include <cstdio>
#include <vector>

using std::vector;
FILE *fin = freopen("cuplaj.in", "r", stdin);
FILE *fout = freopen("cuplaj.out", "w", stdout);

const int kMaxN = 1 + 10000;

/*-------- Input data --------*/
int N, M, E;
vector<int > graph[kMaxN];
/*-------- Cuplaj --------*/
bool checked[kMaxN];
int left[kMaxN], right[kMaxN];

int cuplaj;
/*-------- --------*/

void ReadInput() {
    scanf("%d%d%d", &N, &M, &E);
    for(int i = 1; i <= E; i++) {
        int u, v; scanf("%d%d", &u, &v);
        graph[u].push_back(v);
    }
}

bool PairUp(int node) {
    if(checked[node] == true) {
        return false;
    } else {
        checked[node] = true;
    }

    for(int nxt : graph[node]) {
        if(!right[nxt]) {
            left[node] = nxt;
            right[nxt] = node;
            cuplaj ++;
            return true;
        }
    }

    for(int nxt : graph[node]) {
        if(PairUp(right[nxt])) {
            left[node] = nxt;
            right[nxt] = node;
            return true;
        }
    }

    return false;
}

void HopcroftKarp() {
    bool ok;
    do {
        for(int i = 1; i <= N; i++) {
            checked[i] = false;
        }
        ok = false;
        for(int i = 1; i <= N; i++) {
            if(!left[i]) {
                ok |= PairUp(i);
            }
        }
    }while(ok);
}

void WriteOutput() {
    printf("%d\n", cuplaj);
    for(int i = 1; i <= N; i++) {
        if(left[i]) {
            printf("%d %d\n", i, left[i]);
        }
    }
}

int main() {
    ReadInput();
    HopcroftKarp();
    WriteOutput();
    return 0;
}