Cod sursa(job #938750)

Utilizator GaborGabrielFMI - GabrielG GaborGabriel Data 13 aprilie 2013 19:01:27
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <vector>
#include <fstream>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

#pragma region Global Variables

const int maxn = 10003;

int num_left, num_right, edges;
vector<int> graph[maxn], lleft, rright, visited;

#pragma endregion

//Try to connect the v vertex from the left set to one from the right set
int MakeConnection(int v)
{
	//Local variables
	vector<int>::iterator it;

	//If there is already a connection made from this vertex, return 0;
	if(visited[v] == 1)
		return 0;

	//Set the v vertex as visitated
	visited[v] = 1;

	//Search in all the neighbors
	for(it = graph[v].begin(); it != graph[v].end(); it++)
		if(!rright[*it])
		{
			lleft[v] = *it;
			rright[*it] = v;
			return 1;
		}

	//If there are two points in the first set wich are pointing to the same place, search for another vertex. ......... not very clear
	for(it = graph[v].begin(); it != graph[v].end(); it++)
		if(MakeConnection(rright[*it]))
		{
			lleft[v] = *it;
			rright[*it] = v;
			return 1;
		}
	//If nothing happend, return 0 :)
	return 0;
}

int main()
{
	//Local Variables
	int i, a, b, ok=1, cuplaj = 0;

	//Read the input data
	f>>num_left>>num_right>>edges;
	
	for(i=1;i<=edges;i++)
	{
		f>>a>>b;
		graph[a].push_back(b);
	}

	//Resize and assign values
	visited.resize(num_left+1), lleft.resize(num_left+1), rright.resize(num_right+1);
	lleft.assign(num_left+1, 0), rright.assign(num_right+1, 0);

	//Solve by trying to improve the number of edges while the last time you run you made a change
	while(ok)
	{
		ok = 0;
		visited.assign(num_left+1,0);
		for(i = 1; i <= num_left; i++)
			if( !lleft[i] )
				ok |= MakeConnection(i);
	}

	//Write
	for(i=1; i<=num_left; i++)
		cuplaj += (lleft[i] > 0);

	g<<cuplaj<<'\n';

	for(i=1; i<=num_left; i++)
		if(lleft[i] > 0)
			g<<i<<' '<<lleft[i]<<'\n';

	return 0;
}