Cod sursa(job #1212365)

Utilizator vasile_pojogaPojoga Vasile vasile_pojoga Data 24 iulie 2014 15:20:41
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

void read();
void solve();
bool couple(int x);
int getNumberOfCouples();
void print();

vector<int> G[10005];
int matchR[10005], matchL[10005];
bool used[10005];
int N,M,E,COUPLES;

int main()
{
	read();
	solve();
	print();
	return 0;
}

void read()
{
	int x,y;
	ifstream fin("cuplaj.in");
	fin>>N>>M>>E;
	for(int i=0;i<E;i++)
	{
		fin>>x>>y;
		G[x].push_back(y);
	}
}

void solve()
{
	bool wasChanged = true;
	while(wasChanged)
	{
		wasChanged = false;
		memset(used,false,sizeof(used));
		for(int i=1;i<=N;i++)
		{
			if(matchL[i] == 0)
			{
				wasChanged = wasChanged || couple(i);
			}
		}
	}
	COUPLES = getNumberOfCouples();
}

bool couple(int x)
{
	if(used[x])
	{
		return false;
	}
	else
	{
		used[x] = true;
		for(unsigned int i=0;i<G[x].size();i++)
		{
			if(matchR[G[x][i]] == 0)
			{
				matchR[G[x][i]] = x;
				matchL[x] = G[x][i];
				return true;
			}
		}
		for(unsigned int i=0;i<G[x].size();i++)
		{
			if(couple(matchR[G[x][i]]))
			{
				matchL[x] = G[x][i];
				matchR[G[x][i]] = x;
				return true;
			}
		}
		return false;
	}
}

int getNumberOfCouples()
{
	int result = 0;
	for(int i=1;i<=N;i++)
	{
		if(matchL[i] > 0)
		{
			result++;
		}
	}
	return result;
}

void print()
{
	ofstream fout("cuplaj.out");
	fout<<COUPLES<<'\n';
	for(int i=1;i<=N;i++)
	{
		if(matchL[i] > 0)
		{
			fout<<i<<' '<<matchL[i]<<'\n';
		}
	}
}