Cod sursa(job #927844)

Utilizator fhandreiAndrei Hareza fhandrei Data 26 martie 2013 08:39:11
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
// Include
#include <fstream>
#include <vector>
using namespace std;

// Constante
const int sz = (int)1e4+1;

// Functii
bool change(int node);

// Variabile
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");

int leftNodes, rightNodes, edges;

int Left[sz], Right[sz];
bool canChange[sz];

vector<int> graph[sz];

// Main
int main()
{
	in >> leftNodes >> rightNodes >> edges;
	
	int rFrom, rTo;
	while(edges--)
	{
		in >> rFrom >> rTo;
		graph[rFrom].push_back(rTo);
	}
	
	bool notReady;
	do
	{
		notReady = false;
		memset(canChange, true, sizeof(canChange));
		for(int i=1 ; i<=leftNodes ; ++i)
			if(!Left[i])
				notReady |= change(i);
	} while(notReady);
	
	int answer = 0;
	for(int i=1 ; i<=leftNodes ; ++i)
		if(Left[i])
			++answer;
	
	out << answer << '\n';
	
	for(int i=1 ; i<=leftNodes ; ++i)
		if(Left[i])
			out << i << ' ' << Left[i] << '\n';
	
	in.close();
	out.close();
	return 0;
}

bool change(int node)
{
	if(!canChange[node])
		return false;
	
	canChange[node] = false;
	
	vector<int>::iterator it, end;
	for(it=graph[node].begin(), end=graph[node].end() ; it!=end ; ++it)
	{
		if(!Right[*it])
		{
			Left[node] = *it;
			Right[*it] = node;
			return true;
		}
	}
	
	for(it=graph[node].begin(), end=graph[node].end() ; it!=end ; ++it)
	{
		if(change(Right[*it]))
		{
			Left[node] = *it;
			Right[*it] = node;
			return true;
		}
	}
	
	return false;
}