Cod sursa(job #3168733)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 13 noiembrie 2023 10:17:13
Problema Cuplaj maxim in graf bipartit Scor 4
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

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

const int kN = 1e4;

int l[kN], r[kN];
vector<int> adj[kN];
bool vis[kN];

bool pairUp(int u) {
	if(vis[u]) {
		return 0;
	}
	vis[u] = 1;
	for(const auto &it: adj[u]) {
		if(!r[it]) {
			l[u] = it;
			r[it] = u;
			return 1;
		}
	}
	for(const auto &it: adj[u]) {
		if(pairUp(r[it])) {
			l[u] = it;
			r[it] = u;
			return 1;
		}
	}
	return 0;
}

int main() {
	int n, m, e;
	fin >> n >> m >> e;
	for(int i = 0; i < e; i++) {
		int u, v;
		fin >> u >> v;
		u--; v--;
		adj[u].emplace_back(v);
	}

	bool matching = 1;
	while(matching) {
		matching = 0;
		for(int i = 0; i < n; i++) {
			if(!l[i] && pairUp(i)) {
				matching = 1;
			}
		}
	}

	int max_match = 0;
	for(int i = 0; i < n; i++) {
		if(l[i]) {
			max_match++;
		}
	}
	fout << max_match << '\n';
	for(int i = 0; i < n; i++) {
		if(l[i]) {
			fout << i + 1 << " " << l[i] + 1 << '\n';
		}
	}
	return 0;
}