Cod sursa(job #2651274)

Utilizator ardutgamerAndrei Bancila ardutgamer Data 21 septembrie 2020 23:09:04
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int NMAX = 100005;
const int INF = 2e9 + 5;
const int NIL = 0;

vector<int>G[NMAX];
int pereche[NMAX], dist[NMAX];
int n, m, p;

int bfs()
{
	queue<int>q;
	dist[NIL] = INF;
	for (int i = 1; i <= n; i++)
	{
		if (pereche[i])
			dist[i] = INF;
		else
		{
			dist[i] = 0;
			q.push(i);
		}
	}
	while (!q.empty())
	{
		int u = q.front();
		q.pop();
		if (u)
		{
			for (int v : G[u])
			{
				if (dist[pereche[v]] == INF)
				{
					dist[pereche[v]] = dist[u] + 1;
					q.push(pereche[v]);
				}
			}
		}
	}
	return (dist[NIL] != INF);
}

int dfs(int u)
{
	if (u)
	{
		for (int v : G[u])
		{
			if (dist[u] + 1 == dist[pereche[v]])
				if (dfs(pereche[v]))
				{
					pereche[v] = u;
					pereche[u] = v;
					return true;
				}
		}
		dist[u] = INF;
		return false;
	}
	return true;
}

int hopcroftKarp()
{
	int nrPerechi = 0;
	for (int i = 1; i <= n + m; i++)
		pereche[i] = 0;
	while (bfs())
	{
		for (int i = 1; i <= n; i++)
			if (!pereche[i] && dfs(i))
				nrPerechi++;
	}
	return nrPerechi;
}

void read()
{
	int x, y;
	fin >> n >> m >> p;
	while (p--)
	{
		fin >> x >> y;
		G[x].push_back(y + n);
		G[y + n].push_back(x);
	}
}

void solve()
{
	int nrPerechi = hopcroftKarp();
	fout << nrPerechi << "\n";
	for (int i = 1; i <= n; i++)
		if (pereche[i])
			fout << i << " " << pereche[i] - n << "\n";
}

int main()
{
	read();
	solve();
	return 0;
}