Cod sursa(job #3318320)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 27 octombrie 2025 23:01:02
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <vector>

const int32_t MAX_N = 10000;

std::vector<int32_t> adj[MAX_N];
int32_t left[MAX_N], right[MAX_N];
bool used[MAX_N];

bool Pairup(int32_t node) {
	if(used[node])
		return false;
	used[node] = true;

	for(int32_t next : adj[node]) {
		if(right[next] == -1) {
			left[node] = next;
			right[next] = node;

			return true;
		}
	}
	for(int32_t next : adj[node]) {
		if(Pairup(right[next])) {
			left[node] = next;
			right[next] = node;
		
			return true;
		}
	}

	return false;
}

int main() {
	std::ifstream fin("cuplaj.in");
	std::ofstream fout("cuplaj.out");

	int32_t n, m, e;
	fin >> n >> m >> e;

	for(int32_t i = 0; i != e; ++i) {
		int32_t x, y;
		fin >> x >> y;
		--x; --y;

		adj[x].push_back(y);
	}

	for(int32_t i = 0; i != n; ++i)
		left[i] = -1;
	for(int32_t i = 0; i != m; ++i)
		right[i] = -1;
	
	bool modified;
	do {
		modified = false;
		for(int32_t i = 0; i != n; ++i) {
			if(left[i] == -1)
				modified = modified || Pairup(i);
		}

		for(int32_t i = 0; i != n; ++i)
			used[i] = false;
	} while(modified);

	int32_t count = 0;
	for(int32_t i = 0; i != n; ++i)
		count += (int32_t)(left[i] != -1);
	
	fout << count << '\n';
	for(int32_t i = 0; i != n; ++i) {
		if(left[i] != -1)
			fout << (i + 1) << ' ' << (left[i] + 1) << '\n';
	}
	
	fin.close();
	fout.close();

	return 0;
}