Cod sursa(job #879338)

Utilizator fhandreiAndrei Hareza fhandrei Data 15 februarie 2013 11:45:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
// Include
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;

// Definitii
#define pb push_back

// Constante
const int sz = (int)1e5+8;

// Functii
bool link(int node);

// Variabile
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");

bool Fixed[sz];
int leftNodes, rightNodes, edges;
int Left[sz], Right[sz];

vector<int> graph[sz];

// Main
int main()
{
	in >> leftNodes >> rightNodes >> edges;
	
	int rFrom, rTo;
	while(edges--)
	{
		in >> rFrom >> rTo;
		graph[rFrom].pb(rTo);
	}
	
	bool ok;
	do
	{
		ok = false;
		memset(Fixed, false, sizeof(Fixed));
		for(int i=1 ; i<=leftNodes ; ++i)
			if(!Right[i])
				ok |= link(i);
	} while(ok);
	
	int answer = 0;
	for(int i=1 ; i<=leftNodes ; ++i)
		answer += Right[i]? 1 : 0;
	
	out << answer << '\n';
	
	for(int i=1 ; i<=leftNodes ; ++i)
		if(Right[i])
			out << i << ' ' << Right[i] << '\n';
	
	in.close();
	out.close();
	return 0;
}


bool link(int node)
{
	if(Fixed[node])
		return false;
	Fixed[node] = true;
	vector<int>::iterator it, end=graph[node].end();
	for(it=graph[node].begin() ; it!=end ; ++it)
	{
		if(!Left[*it])
		{
			Left[*it] = node;
			Right[node] = *it;
			return true;
		}
	}
	for(it=graph[node].begin() ; it!=end ; ++it)
	{
		if(link(Left[*it]))
		{
			Left[*it] = node;
			Right[node] = *it;
			return true;
		}
	}
	return false;
}