Cod sursa(job #2692838)

Utilizator lauratenderLaura Tender lauratender Data 3 ianuarie 2021 22:10:46
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
using namespace std;

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

const int N = 10000;
int n, m, e, l[N + 1], r[N + 1], ans;
vector <int> graph[N + 1];
bool vis[N + 1];

bool dfs(int node)
{
	if (vis[node])
		return false;
	vis[node] = true;

	for (int nbh: graph[node])
    {
		if (!r[nbh] || dfs(r[nbh]))
		{
			l[node] = nbh;
			r[nbh] = node;
			return true;
		}
	}
	return false;
}

void cuplaj()
{
    bool ok = true;
	while (ok)
    {
		ok = false;
		for (int i = 1; i <= n; ++i)
			vis[i] = false;

		for (int i = 1; i <= n; ++i)
		{
			// daca nu este cuplat si gasim pereche
			if (!l[i] && dfs(i))
			{
				ok = true;
				ans++;
			}
		}
	}
}

int main(){


	in >> n >> m >> e;

	for (int i = 0; i < e; ++i)
    {
		int a, b;
		in >> a >> b;
		graph[a].push_back(b);
	}

    cuplaj();

	out << ans << '\n';
	for (int i = 1; i <= n; ++i)
		if (l[i])
			out << i << ' ' << l[i] << '\n';

	return 0;
}