Cod sursa(job #2410092)

Utilizator LucaSeriSeritan Luca LucaSeri Data 19 aprilie 2019 18:34:07
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
 
using namespace std;

const int MAXN = 1e4 + 1;

int l[MAXN];
int r[MAXN];
int viz[MAXN];
int step = 0;
vector< int > gr[MAXN];
int ans = 0;

bool cuplaj(int node) {
	if(viz[node] == step) return false;
	viz[node] = step;
	for(auto &x : gr[node]) {
		if(!l[x]) {
			l[x] = node;
			r[node] = x;
			++ans;
			return true;
		}
	}

	for(auto &x : gr[node]) {
		if(cuplaj(l[x])) {
			l[x] = node;
			r[node] = x;
			return true;
		}
	}

	return false;
}

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("cuplaj.in", "r", stdin);
		freopen("cuplaj.out", "w", stdout);
	#endif
 
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	int n, m;
	cin >> n >> m;

	int e;
	cin >> e;

	for(int i = 0; i < e; ++i) {
		int a, b;
		cin >> a >> b;
		gr[a].emplace_back(b);
	} 

	bool ok = true;
	while(ok) {
		ok = false;
		++step;
		for(int i = 1; i <= n; ++i) if(!r[i]) ok |= cuplaj(i);
	}

	cout << ans << '\n';

	for(int i = 1; i <= n; ++i) {
		if(r[i]) {
			cout << i << ' ' << r[i] << '\n';
		}
	}
	return 0;
}