Cod sursa(job #2866976)

Utilizator Madalin_IonutFocsa Ionut-Madalin Madalin_Ionut Data 10 martie 2022 09:31:28
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, e;
int A[10003], B[10003];
vector<int> L[10003];
bitset<10003> viz;

void Citire()
{
	int i, x, y;
	fin >> n >> m >> e;
	for (i = 1; i <= e; i++)
	{
		fin >> x >> y;
		L[x].push_back(y);
	}
}

int Cuplaj(int k)
{
	if (viz[k]) return 0;
	viz[k] = 1;
	for(int x : L[k]) ///cautam un posibil candidat
		if (B[x] == 0)
		{
			B[x] = k;
			A[k] = x;
			/// am gasit o solutie pe care o vom retine
			return 1;
		}
	///nu am gasit niciun adiacent necuplat
	///cautam un adiacent care poate fi decuplat
	///procesul se repeta pentru nodul de la care si-a pierdut perechea
	for(int x : L[k])
		if (Cuplaj(B[x]))
		{
			B[x] = k;
			A[k] = x;
			/// am gasit o solutie pe care o vom retine
			return 1;
		}
	///nu are pereche. RIP
	return 0;
}

void Cuplaj_Max_Graf_Bipartit()
{
	int i, cnt = 0;
	bool done = false;
	while (!done)
	{
		done = true;
		viz.reset();
		/// Atat timp cat un element inca mai poate fi cuplat
		/// vom continua. "All we have to do is keep moving forward.
		/// Isn't that right Eren?"
		for (i = 1; i <= n; i++)
			if (A[i] == 0 && Cuplaj(i))
			{
				done = false;
				cnt++;
			}
	}
	fout << cnt << "\n";
	for (i = 1; i <= n; i++)
		if (A[i] != 0)
			fout << i << " " << A[i] << "\n";
	fout.close();
}

int main()
{
	Citire();
	Cuplaj_Max_Graf_Bipartit();
}