Cod sursa(job #1442253)

Utilizator nytr0gennytr0gen nytr0gen Data 24 mai 2015 20:24:24
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>
#include <vector>
#include <bitset>

using namespace std;

const int NMAX = 10000 + 1;
vector<int> graf[NMAX];
vector<int> st(NMAX, 0), dr(NMAX, 0);
bitset<NMAX> viz;

bool cuplaj(int nod) {
    if (viz[nod]) return false;
    viz[nod] = true;

    for (int v: graf[nod]) {
	    if (!dr[v]) {
		    dr[v] = nod;
		    st[nod] = v;

		    return true;
        }
    }

	for (int v: graf[nod]) {
		if (cuplaj(dr[v])) {
			dr[v] = nod;
			st[nod] = v;

			return true;
		}
	}

    return false;
}

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

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

	bool hasChange;
	do {
		hasChange = false;
		viz.reset();

		for (int v = 1; v <= N; ++v) {
			if (!st[v] && cuplaj(v)) {
				hasChange = true;
			}
		}
	} while (hasChange);

	int cuplate = 0;
	for (int v = 1; v <= N; ++v) {
		cuplate += !!st[v];
	}
	printf("%d\n", cuplate);

    for (int v = 1; v <= N; ++v) {
	    if (st[v]) {
		    printf("%d %d\n", v, st[v]);
	    }
    }

    return 0;
}