Cod sursa(job #918573)

Utilizator vlad.maneaVlad Manea vlad.manea Data 18 martie 2013 23:26:13
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;

#define NMAX 10001
#define INFILE "cuplaj.in"
#define OUTFILE "cuplaj.out"
int N, M, E;
vector<int> lists[NMAX];
int Nmatch[NMAX];
int Mmatch[NMAX];
bool Nused[NMAX];

void read()
{
	int x, y, c;
	ifstream fin(INFILE);
	fin >> N >> M >> E;

	while (E--)
	{
		fin >> x >> y;
		lists[x].push_back(y);
	}
	
	fin.close();
}

bool match(int node)
{
	if (Nused[node] == true)
	{
		return false;
	}

	Nused[node] = true;

	// try to match with something
	for (int index = 0; index < lists[node].size(); ++index)
	{
		int pal = lists[node][index];

		if (Mmatch[pal] == 0)
		{
			Nmatch[node] = pal;
			Mmatch[pal] = node;
			return true;
		}
	}

	// try to make others match
	for (int index = 0; index < lists[node].size(); ++index)
	{
		int pal = lists[node][index];

		if (match(Mmatch[pal]))
		{
			Nmatch[node] = pal;
			Mmatch[pal] = node;
			return true;
		}
	}
	
	return false;
}

void solve()
{
	while (true)
	{
		bool matched = false;

		for (int node = 1; node <= N; ++node)
		{
			Nused[node] = false;
		}

		for (int node = 1; node <= N; ++node)
		{
			if (Nmatch[node] == 0)
			{
				matched |= match(node);
			}
		}

		if (matched == false)
		{
			break;
		}
	}
}

void write()
{
	ofstream fout(OUTFILE);
	
	int count = 0;

	for (int node = 1; node <= N; ++node)
	{
		if (Nmatch[node] != 0)
		{
			++count;
		}
	}

	fout << count << '\n';

	for (int node = 1; node <= N; ++node)
	{
		if (Nmatch[node] != 0)
		{
			fout << node << ' ' << Nmatch[node] << '\n';
		}
	}

	fout.close();
}

int main()
{
	read();
	solve();
	write();
}