Cod sursa(job #2386439)

Utilizator gabib97Gabriel Boroghina gabib97 Data 22 martie 2019 22:33:33
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

#define N 10005

using namespace std;

int n, m, e, p1[N], p2[N];
vector<int> G[N];
vector<pair<int, int>> couples;
bool o[N];

int match(int s) {
	if (o[s]) return 0;
	o[s] = 1;

	for (int x : G[s])
		if (!p2[x]) {
			p1[s] = x;
			p2[x] = s;
			return 1;
		}

	for (int x : G[s])
		if (match(p2[x])) {
			p1[s] = x;
			p2[x] = s;
			return 1;
		}

	return 0;
}

int main() {
	ifstream cin("cuplaj.in");
	ofstream cout("cuplaj.out");

	cin >> n >> m >> e;

	int i, x, y;
	for (i = 1; i <= e; i++) { 
		cin >> x >> y;
		G[x].push_back(y);
	}

	int cuplaj;
	do {
		cuplaj = 0;
		memset(o, 0, sizeof(o));

		for (i = 1; i <= n; i++)
			if (!p1[i])
				cuplaj += match(i);
	} while (cuplaj);

	for (i = 1; i <= n; i++) 
		if (p1[i])
			couples.push_back(make_pair(i, p1[i]));

	cout << couples.size() << '\n';
	for (auto p : couples)
		cout << p.first << " " << p.second << '\n';
	return 0;
}