Cod sursa(job #2947405)

Utilizator VladNANegoita Vlad-Andrei VladNA Data 26 noiembrie 2022 01:00:18
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
#define NMAX 10005

#pragma GCC optimize("Ofast")

using namespace std;

vector<int> adj[NMAX];
int to[NMAX], from[NMAX];
bool viz[NMAX];

int tryrematch(int node) {

	viz[node] = true;
	for (int neighbour : adj[node]) {
		if (!from[neighbour] || (!viz[from[neighbour]] && tryrematch(from[neighbour]))) {
			from[neighbour] = node;
			to[node] = neighbour;
			return 1;
		}
	}

	return 0;
}

int main() {

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

	int n, m, e;
	in >> n >> m >> e;
	for (int edge = 1, x, y; edge <= e; ++edge) {
		in >> x >> y;
		adj[x].push_back(y);
	}

	in.close();

	for (int i = 1; i <= n; ++i) {
		if (to[i])
			continue;

		memset(viz, 0, sizeof(viz));
		tryrematch(i);
	}

	vector <pair<int, int>> result;
	for (int i = 1; i <= n; ++i)
		if (to[i])
			result.push_back({i, to[i]});

	out << result.size() << '\n';
	for (pair<int, int> p : result)
		out << p.first << ' ' << p.second << '\n';

	out.close();

	return 0;
}