Cod sursa(job #3348920)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 24 martie 2026 17:41:49
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

const int nmax = 1e5 + 5;

int n, m, p1[nmax], p2[nmax], fr[nmax];
vector<int> v[nmax];

bool mbm(int node)
{
	if (fr[node]) return false;

	fr[node] = 1;
	for(auto x : v[node])
		if (!p2[x]) {
			p2[x] = node;
			p1[node] = x;
			return true;
		}

	for(auto x : v[node])
		if (mbm(p2[x])) {
			p2[x] = node;
			p1[node] = x;
			return true;
		}

	return false;
}

void cuplaj()
{
	int oki = 1;
	while (oki)
	{
		oki = 0;
		fill(fr + 1, fr + (n + m) + 1, 0);

		for (int i = 1; i <= n; i++)
			if (!p1[i] && mbm(i)) oki = 1;
	}
}

int main()
{
	int q; f >> n >> m >> q;
	for (; q >= 1; q--)
	{
		int x, y; f >> x >> y;
		v[x].push_back(y + n);
		v[y + n].push_back(x);
	}

	cuplaj();

	vector<pair<int, int>> ans; ans.clear();
	for (int i = 1; i <= n; i++)
		if (p1[i]) ans.push_back({ i, p1[i] - n });
	
	g << ans.size() << '\n';
	for (auto x : ans) g << x.first << " " << x.second << '\n';
	return 0;
}