Cod sursa(job #872073)

Utilizator cosminpdrfischer2004 cosminp Data 5 februarie 2013 19:06:20
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <vector>

#define MAX_SIZE	10001
#define NONE		-1

using namespace std;

int 			m, n, max_pairs;
int				Left[MAX_SIZE], Right[MAX_SIZE];
int				Visited[MAX_SIZE];
vector<int>		Neighbors[MAX_SIZE];


int find_path(int u)
{
	if (Visited[u]) return false;

	Visited[u] = 1;
	for (vector<int>::iterator it = Neighbors[u].begin(); it != Neighbors[u].end(); ++it)
	{
		if ( (Right[*it] == NONE) || find_path(Right[*it]) )
		{
			Left[u] = *it;
			Right[*it] = u;
			return 1;
		}
	}

	return 0;
}


void max_matching()
{
	bool	found_path = true;

	max_pairs = 0;
	memset(Left, NONE, MAX_SIZE*sizeof(int));
	memset(Right, NONE, MAX_SIZE*sizeof(int));

	while (found_path)
	{
		found_path = false;
		memset(Visited, false, MAX_SIZE*sizeof(int));

		for (int i = 0; i < n; i++)
		{
			if ( (Left[i] == NONE) && find_path(i) )
			{
				found_path = true;
				max_pairs++;
			}
		}
	}
}


int main()
{
	fstream 		f, g;
	int				e, u, v;

	f.open("cuplaj.in", ios::in);
	g.open("cuplaj.out", ios::out);

	f >> n >> m >> e;
	for (int i = 0; i < e; i++)
	{
		f >> u >> v;
		Neighbors[u - 1].push_back(v - 1);
	}

	max_matching();

	g << max_pairs << endl;
	for (int i = 0; i < n; i++)
	{
		if (Left[i] != NONE)
		{
			g << i + 1 << " " << Left[i] + 1 << endl;
		}
	}

	g.close();
	f.close();

	return 0;
}