Cod sursa(job #935420)

Utilizator alex_unixPetenchea Alexandru alex_unix Data 3 aprilie 2013 14:10:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb

#include <cstdio>
#include <cstring>
#include <vector>

const int MAX_SIZE(10001);

int n, m, e, match;

std::vector<int> graph [MAX_SIZE];
int left [MAX_SIZE];
int right [MAX_SIZE];

bool mark [MAX_SIZE];

inline void read (void)
{
	std::freopen("cuplaj.in","r",stdin);
	std::scanf("%d %d %d",&n,&m,&e);
	for (int i(0), a, b ; i < e ; ++i)
	{
		std::scanf("%d %d",&a,&b);
		graph[a].push_back(b);
	}
	std::fclose(stdin);
}

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

bool DepthFirstSearch (int node)
{
	if (mark[node])
		return false;
	mark[node] = true;
	for (int i(0), end(graph[node].size()) ; i < end ; ++i)
		if (!right[graph[node][i]] || DepthFirstSearch(right[graph[node][i]]))
		{
			left[node] = graph[node][i];
			right[graph[node][i]] = node;
			return true;
		}
	return false;
}

inline void HopcroftKarp (void)
{
	int i;
	bool ok(true);
	while (ok)
	{
		ok = false;
		std::memset(mark + 1,0,n);
		for (i = 1 ; i <= n ; ++i)
			if (!left[i] && DepthFirstSearch(i))
			{
				++match;
				ok = true;
			}
	}
}

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