Cod sursa(job #2713893)

Utilizator sebimihMihalache Sebastian sebimih Data 28 februarie 2021 20:21:32
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

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

const int N = 1e4 + 5;

int n, m, e;
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()
{
	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 = true;
	while (ok)
	{
		ok = false;
		vizitat.assign(n + 1, false);

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

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

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