Cod sursa(job #829002)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 4 decembrie 2012 19:23:38
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb

#include <cstdio>
#include <cstring>

const int MAX_SIZE(10001);

int n, m, e, matching;

int left [MAX_SIZE];
int right [MAX_SIZE];

bool search [MAX_SIZE];

struct edge
{
	int node;
	struct edge * next;
} *graph [MAX_SIZE];

inline void add (int x, int y)
{
	struct edge *new_edge(new struct edge);
	new_edge->node = y;
	new_edge->next = graph[x];
	graph[x] = new_edge;
}

inline void read (void)
{
	std::freopen("cuplaj.in","r",stdin);
	std::scanf("%d%d%d",&n,&m,&e);
	int x, y;
	for (int counter(0) ; counter < e ; ++counter)
	{
		std::scanf("%d%d",&x,&y);
		add(x,y);
	}
	std::fclose(stdin);
}

inline void print (void)
{
	std::freopen("cuplaj.out","w",stdout);
	std::printf("%d\n",matching);
	for (int vertex = 1 ; vertex <= n ; ++vertex)
		if (left[vertex])
			std::printf("%d %d\n",vertex,left[vertex]);
	std::fclose(stdout);
}

bool DepthFirstSearch (int vertex)
{
	if (search[vertex])
		return false;
	search[vertex] = true;
	for (struct edge *iterator(graph[vertex]) ; iterator ; iterator = iterator->next)
		if (!right[iterator->node] || DepthFirstSearch(right[iterator->node]))
		{
			left[vertex] = iterator->node;
			right[iterator->node] = vertex;
			return true;
		}
	return false;
}

inline void HopcroftKarp (void)
{
	int vertex;
	bool match;
	do
	{
		match = false;
		std::memset(search + 1,0,n);
		for (vertex = 1 ; vertex <= n ; ++vertex)
			if (!left[vertex])
				if (DepthFirstSearch(vertex))
				{
					match = true;
					++matching;
				}
	}
	while (match);
}

int main (void)
{
	read();
	HopcroftKarp();
	print();
	return 0;
}