Cod sursa(job #1391157)

Utilizator mircea.dobreanuMircea Dobreanu mircea.dobreanu Data 17 martie 2015 17:51:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bitset>
#include <fstream>
#include <vector>
using namespace std;

const int kMax = 2e4 + 5;
int n, m;
int match[kMax];
vector<int> g[kMax];
bitset<kMax> vis;

void read()
{
	ifstream fin("cuplaj.in");
	int e;
	fin >> n >> m >> e;
	while (e--)
	{
		int u, v;
		fin >> u >> v;
		v += n;
		g[u].push_back(v);
	}
	fin.close();
}

void write()
{
	ofstream fout("cuplaj.out");
	int noMatches = 0;
	for (int i = 1; i <= n; ++i)
		if (match[i])
			++noMatches;

	fout << noMatches << '\n';
	for (int i = 1; i <= n; ++i)
		if (match[i])
			fout << i << ' ' << match[i] - n<< '\n';

	fout.close();
}

bool foundMatchFor(int u)
{
	if (vis[u])
		return false;
	vis[u] = true;

	for (size_t i = 0; i < g[u].size(); ++i)
	{
		int v = g[u][i];
		if (!match[v])
		{
			match[u] = v;
			match[v] = u;
			return true;
		}
	}

	for (size_t i = 0; i < g[u].size(); ++i)
	{
		int v = g[u][i];
		if (foundMatchFor(match[v]))
		{
			match[u] = v;
			match[v] = u;
			return true;
		}
	}
	return false;
}

void hopcroftKarp()
{
	bool changed;
	do
	{
		changed = false;
		vis.reset();

		for (int i = 1; i <= n; ++i)
			if (!match[i])
				changed |= foundMatchFor(i);
	}
	while (changed);
}


int main()
{
	read();
	hopcroftKarp();
	write();
	return 0;
}