Cod sursa(job #2709642)

Utilizator sebimihMihalache Sebastian sebimih Data 20 februarie 2021 19:55:14
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 1e4 + 5;

vector<int> g[N], leftCoupled, rightCoupled;
vector<bool> vizitat;

bool match(int node)
{
	if (vizitat[node])
		return false;

	vizitat[node] = true;

	for (int next : g[node])
	{
		if (!rightCoupled[next] || match(rightCoupled[next]))
		{
			leftCoupled[node] = next;
			rightCoupled[next] = node;
			return true;
		}
	}

	return false;
}

int main()
{
	int n, m, e;
	fin >> n >> m >> e;

	leftCoupled.resize(n + 1);
	rightCoupled.resize(m + 1);
	for (int i = 0; i < e; i++)
	{
		int x, y;
		fin >> x >> y;
		g[x].push_back(y);
	}

	bool ok = false;
	do
	{
		ok = false;
		vizitat.assign(n + m + 1, false);

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

	int ans = 0;
	for (int i = 1; i <= n; i++)
		if (leftCoupled[i])
			ans++;

	cout << ans << '\n';
	for (int i = 1; i <= n; i++)
		if (leftCoupled[i])
			cout << i << ' ' << leftCoupled[i] << '\n';
}