Cod sursa(job #1239943)

Utilizator DuxarFII-Stefan-Negrus Duxar Data 10 octombrie 2014 00:05:58
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include<vector>
#include<fstream>
#include<cstdio>

using namespace std;

vector< vector<int> > edges;
vector<int> left_match, right_match;
int left_N, right_M, E, cnt;
vector<bool> visited;

bool found_pair(int iam);

int main() {
#ifdef INFOARENA
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out", "w", stdout);
#else
	freopen("input", "r", stdin);
#endif
	int i, x, y;
	bool new_pair;

	scanf("%d %d %d", &left_N, &right_M, &E);

	edges.resize(left_N + 1);
	left_match.resize(right_M + 1);
	right_match.resize(left_N + 1);
	visited.resize(left_N + 1);

	for (i = 0; i < E; ++i) {
		scanf("%d %d", &x, &y);
		edges[x].push_back(y);
	}

	new_pair = true;
	while(new_pair) {
		new_pair = false;
		fill(visited.begin(), visited.end(), false);
		for (i = 1; i <= left_N; ++i) {
			if (right_match[i] == 0) {
				new_pair = found_pair(i) || new_pair;
			}
		}
	}

	for (i = 1; i <= left_N; ++i) {
		cnt += right_match[i] > 0;
	}

	printf("%d\n", cnt);
	for (i = 1; i <= left_N; ++i) {
		if (right_match[i]){
			printf("%d %d\n", i, right_match[i]);
		}
	}
	return 0;
}

bool found_pair(int iam) {
	if (visited[iam]) {
		return false;
	}
	visited[iam] = true;
	for (auto to: edges[iam]) {
		if (left_match[to] == 0 || found_pair(left_match[to])) {
			left_match[to] = iam;
			right_match[iam] = to;
			return true;
		}
	}
	return false;
}