Cod sursa(job #809831)

Utilizator ahmed.abdraboahmed.abdrabo ahmed.abdrabo Data 9 noiembrie 2012 04:57:16
Problema Cuplaj maxim in graf bipartit Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

inline int next_int() {
	int n = 0;
	char c = getchar_unlocked();
	while (!('0' <= c && c <= '9')) {
		c = getchar_unlocked();
	}
	while ('0' <= c && c <= '9') {
		n = n * 10 + c - '0';
		c = getchar_unlocked();
	}
	return n;
}

const int V = 10000 + 10;
const int E = 100000 + 10;
const int NIL = 0;

int ec, eb[V], en[E], et[E];
int n, m, XY[V], YX[V], d[V];
bool seen[V];

bool bfs() {
	queue<int> Q;
	for (int u = 1; u <= n; u++) {
		if (XY[u] == NIL) {
			d[u] = 0;
			Q.push(u);
		} else {
			d[u] = 1 << 30;
		}
	}
	d[NIL] = 1 << 30;
	while (!Q.empty()) {
		int u = Q.front();
		Q.pop();
		for (int e = eb[u]; e != -1; e = en[e]) {
			int v = et[e];
			if (d[YX[v]] == 1 << 30) {
				d[YX[v]] = d[u] + 1;
				Q.push(YX[v]);
			}
		}
	}
	return d[NIL] != 1 << 30;
}

bool dfs(int u) {
	if (u != NIL) {
		for (int e = eb[u]; e != -1; e = en[e]) {
			int v = et[e];
			if (d[YX[v]] == d[u] + 1) {
				XY[u] = v;
				YX[v] = u;
				return true;
			}
		}
		d[u] = 1 << 30;
		return false;
	}
	return true;
}

int main() {
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out", "w", stdout);
	memset(eb, -1, sizeof eb);
	n = next_int();
	m = next_int();
	int e = next_int();
	for (int i = 0; i < e; i++) {
		int u = next_int();
		int v = next_int();
		et[ec] = v;
		en[ec] = eb[u];
		eb[u] = ec++;
	}
	int ans = 0;
	while (bfs()) {
		for (int u = 1; u <= n; u++) {
			if (XY[u] == NIL && dfs(u)) {
				ans++;
			}
		}
	}
	printf("%d\n", ans);
	for (int u = 1; u <= n; u++) {
		if (XY[u] != NIL) {
			printf("%d %d\n", u, XY[u]);
		}
	}
	return 0;
}