Cod sursa(job #2962375)

Utilizator AntoniaPopoviciAntonia-Adelina Popovici AntoniaPopovici Data 8 ianuarie 2023 14:40:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
const int N = 1 << 14;

int c, n, m, st[N], dr[N];
vector<int> stanga[N], dreapta[N];
bool viz[N];

void citire()
{
	int e, x, y;
	fin >> n >> m >> e;
	while (e--)
	{
		fin >> x >> y;
		dreapta[x].push_back(y);
		stanga[y].push_back(x);
	}
}

bool cupleaza(int x)
{
	int y;
	if (viz[x])
		return false;
	viz[x] = true;
	for (size_t i = 0; i < dreapta[x].size(); ++i)
	{
		y = dreapta[x][i];
		if (!st[y])
		{
			dr[x] = y;
			st[y] = x;
			return true;
		}
	}
	for (size_t i = 0; i < dreapta[x].size(); ++i)
	{
		y = dreapta[x][i];
		if (cupleaza(st[y]))
		{
			dr[x] = y;
			st[y] = x;
			return true;
		}
	}
	return false;
}

void cuplaj()
{
	int i;
	bool gata;
	do {
		gata = true;
		memset(viz, 0, sizeof(viz));
		for (i = 1; i <= n; ++i)
			if (!dr[i])
			{
				cupleaza(i);
				if (dr[i])
				{
					++c;
					gata = false;
				}
			}
	} while (!gata);
}

void scrie()
{
	fout << c << '\n';
	for (int i = 1; i <= n; ++i)
		if (dr[i])
			fout << i << " " << dr[i] << '\n';
}

int main()
{
	citire();
	cuplaj();
	scrie();
	return 0;
}