Cod sursa(job #3221108)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 5 aprilie 2024 22:12:01
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <vector>

const int32_t MAX_N = 10000;
const int32_t MAX_M = 10000;

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

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

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

		return true;
	}

	for(int32_t next : adj[node]) {
		if(!Pair(right[next]))
			continue;
		
		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 = false;
	do {
		for(int32_t i = 0; i != n; ++i)
			used[i] = false;
		
		modified = false;
		for(int32_t i = 0; i != n; ++i)
			if(left[i] == -1)
				modified = modified || Pair(i);
	} while(modified);

	int32_t count = 0;
	for(int32_t i = 0; i != n; ++i)
		count += 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;
}