Cod sursa(job #1450116)

Utilizator MciprianMMciprianM MciprianM Data 11 iunie 2015 15:09:55
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

static const int MAXN = 10009;
vector<int> G[MAXN];
int matchForL[MAXN];
int matchForR[MAXN];
bool u[MAXN];

bool match_it(int who)
{
	int vec;
	bool success = false;
	u[who] = true;
	for(int i = 0, l = G[who].size(); i < l && !success; i++)
	{
		vec = G[who][i];
		if(vec != matchForL[who]) // edge is white and node was not used
		{
			if(!matchForR[vec]) //end of the ride
			{
				success = true;
			}
			else if(!u[matchForR[vec]])
			{
				success = match_it(matchForR[vec]); //go black
			}
			if(success)
			{
				matchForL[who] = vec;
				matchForR[vec] = who;
			}
		}
	}
	return success;
}

int main()
{
	int n, m, e, x, y;
	ifstream f("cuplaj.in");
	f >> n >> m >> e;
	for(int i = 0; i < e; i++)
	{
		f >> x >> y;
		G[x].push_back(y);
	}
	f.close();
	for(int i = 1; i <= n; i++)
	{
		if(!matchForL[i])
		{
			memset(u, 0, sizeof u);
			match_it(i);
		}
	}
	vector<pair<int, int> > ans;
	for(int i = 1; i <= n; i++)
	{
		if(matchForL[i])
		{
			ans.push_back(pair<int, int>(i, matchForL[i]));
		}
	}
	ofstream g("cuplaj.out");
	g << ans.size() << '\n';
	for(int i = 0, l = ans.size(); i < l; i++)
	{
		g << ans[i].first << ' ' << ans[i].second << '\n';
	}
	g.close();
	return 0;
}