Cod sursa(job #457549)

Utilizator coderninuHasna Robert coderninu Data 20 mai 2010 00:32:31
Problema Cuplaj maxim in graf bipartit Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>

#define Nmax 100

using namespace std;

vector< int > G[Nmax];
vector< bool > uz;
int nrSt, nrDr, nrMuchii, st[Nmax], dr[Nmax], x, y, cuplaj;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

bool cupleaza(int x) // imperecheaza pe x din st cu un nod din dr
{
	if (uz[x]) return false;
	uz[x] = true;
	for (vector< int > :: iterator it = G[x].begin(); it != G[x].end(); ++it)
	{
		if (!dr[*it]) // daca e liber, le cuplez
		{
			st[x] = *it;
			dr[*it] = x;
			return true;
		}
	}
	//nu e nici unu liber.Incerc sa cuplez un vecin cu altcineva
	for (vector< int > :: iterator it = G[x].begin(); it != G[x].end(); ++it)
	{
		if (cupleaza(dr[*it])) //daca am reusit sa cuplez pe dr[*it] cu altcineva, el e liber si il cuplez cu x
		{
			st[x] = *it;
			dr[*it] = x;
			return true;
		}
	}
	return false;
}


int main()
{
	fin >> nrSt >> nrDr >> nrMuchii;
	while (nrMuchii--)
	{
		fin >> x >> y;
		G[x].push_back(y);
	}

	for (bool gata = false; !gata; )
	{
		gata = true;
		uz.assign(nrSt + 1, false);
		for (int i = 1; i <= nrSt; ++i)
		{
			if (!st[i])//daca nu e cuplat
			{
				if (cupleaza(i))
					gata = false;
			}
		}
	}

	for (int i = 1; i <=nrSt; ++i)
		if (st[i])
			++cuplaj;
	fout << cuplaj << endl;
	for (int i = 1; i <= nrSt; ++i)
		if (st[i])
			fout << i << " " << st[i] << endl;
			
	//system("pause");
	return 0;
}