Cod sursa(job #1826771)

Utilizator retrogradLucian Bicsi retrograd Data 10 decembrie 2016 21:02:46
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

struct BipartiteMatcher {
	vector<vector<int>> G;
	vector<int> L, R, Viz;

	BipartiteMatcher(int n, int m) {
		G.resize(n);
		L.resize(n, -1);
		R.resize(m, -1);
		Viz.resize(n);
	}

	void AddEdge(int a, int b) {
		G[a].push_back(b);
	}

	bool Match(int node) {
		if(Viz[node]) 
			return false;
		Viz[node] = true;
	
		for(auto vec : G[node]) {
			if(R[vec] == -1 || Match(R[vec])) {
				L[node] = vec;
				R[vec] = node;
				return true;
			}
		}

		return false;
	}
	void Solve() {
		bool ok = true;
		while(ok) {
			ok = false;
			fill(Viz.begin(), Viz.end(), 0);
			for(int i = 0; i < L.size(); ++i)
				if(L[i] == -1)
					ok |= Match(i);
		}
	}
};

int main() {
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out", "w", stdout);

	int n, m, k;
	cin >> n >> m >> k;
	BipartiteMatcher T(n, m);
	while(k--) {
		int a, b;
		cin >> a >> b;
		T.AddEdge(a - 1, b - 1);
	}

	T.Solve();
	vector<pair<int, int>> Sol;
	for(int i = 0; i < n; ++i)
		if(T.L[i] != -1)
			Sol.emplace_back(i, T.L[i]);

	cout << Sol.size() << endl;
	for(auto p : Sol)
		cout << p.first + 1 << " " << p.second + 1 << '\n';

	return 0;
}