Cod sursa(job #872052)

Utilizator cosminpdrfischer2004 cosminp Data 5 februarie 2013 18:52:07
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 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];
bool			visited[MAX_SIZE];
vector<int>		neighbors[MAX_SIZE];


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

	visited[u] = true;
	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 true;
		}
	}

	return false;
}


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(bool));

		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;
}