Cod sursa(job #1755271)

Utilizator howsiweiHow Si Wei howsiwei Data 9 septembrie 2016 17:59:50
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> al;
vector<int> mt0, mt1;
vector<bool> vis;

bool dfs(int u) {
	vis[u] = true;
	for (int v: al[u]) {
		if (mt1[v] == -1) {
			mt1[v] = u;
			mt0[u] = v;
			return true;
		}
	}
	for (int v: al[u]) {
		if (!vis[mt1[v]] && dfs(mt1[v])) {
			mt1[v] = u;
			mt0[u] = v;
			return true;
		}
	}
	return false;
}

int main() {
#ifdef INFOARENA
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out", "w", stdout);
#endif
	cin.sync_with_stdio(false);
	int n0, n1, m;
	cin >> n0 >> n1 >> m;
	al.assign(n0, {});
	mt0.assign(n0, -1);
	mt1.assign(n1, -1);
	for (int i = 0; i < m; i++) {
		int u, v;
		cin >> u >> v;
		u--, v--;
		al[u].push_back(v);
	}
	// for (int u = 0; u < n0; u++) {
	// 	random_shuffle(al[u].begin(), al[u].end());
	// }
	int nmt = 0;
	bool chg;
	do {
		chg = false;
		vis.assign(n0, false);
		for (int u = 0; u < n0; u++) {
			if (mt0[u] == -1 && !vis[u] && dfs(u)) {
				nmt++;
				chg = true;
			}
		}
	} while (chg);
	printf("%d\n", nmt);
	for (int u = 0; u < n0; u++) {
		if (mt0[u] != -1)
			printf("%d %d\n", u+1, mt0[u]+1);
	}
	return 0;
}