Cod sursa(job #296646)

Utilizator andreisfrentSfrent Andrei andreisfrent Data 4 aprilie 2009 23:21:37
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

#define N 10001

vector<int> g[N];
int l[N], r[N], viz[N];
	
int imperecheaza(int x)
{
	if(viz[x]) return 0;
	viz[x] = 1;
	
	vector<int>::iterator i;
	
	for(i = g[x].begin(); i != g[x].end(); ++i)
	{
		if(r[*i] == 0)
		{
			l[x] = *i;
			r[*i] = x;
			return 1;
		}
	}
	
	for(i = g[x].begin(); i != g[x].end(); ++i)
	{
		if(imperecheaza(r[*i]))
		{
			l[x] = *i;
			r[*i] = x;
			return 1;
		}
	}
	
	return 0;
}

int main()
{
	FILE* fi = fopen("cuplaj.in", "r");
	FILE* fo = fopen("cuplaj.out", "w");
	
	int n, m, e, x, y, i;
	
	fscanf(fi, "%d%d%d", &n, &m, &e);
	
	while(e--) 
	{
		fscanf(fi, "%d%d", &x, &y);
		g[x].push_back(y);
	}
	
	int schimbare = 1;
	
	while(schimbare)
	{
		schimbare = 0;
		memset(viz, 0, sizeof(viz));
		for(i = 1; i <= n; ++i) if(!l[i]) schimbare |= imperecheaza(i);
	}
	
	int nr_comp_cuplate = 0;
	
	for(i = 1; i <= n; ++i) if(l[i]) ++nr_comp_cuplate;
	fprintf(fo, "%d\n", nr_comp_cuplate);
	for(i = 1; i <= n; ++i) if(l[i]) fprintf(fo, "%d %d\n", i, l[i]);
	
	fclose(fi);
	fclose(fo);
	return 0;
}