Cod sursa(job #2820192)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 19 decembrie 2021 23:52:46
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1005;

int n,m,e;
vector<int> G[NMAX];
int match[NMAX], r[NMAX];
bool used[NMAX];

int pairup ( int k ) {
	if (used[k]) return 0;
	used[k] = true;
	for (auto i : G[k]) {
		if (r[i] == 0) {
			match[k] = i;
			r[i] = k;
			return 1;
		}
	}
	for (auto i : G[k]) {
		if (pairup(r[i])) {
			match[k] = i;
			r[i] = k;
			return 1;
		}
	}
	return 0;
}

int main() {
	ifstream fin("cuplaj.in");
	ofstream fout("cuplaj.out");
    fin >> n >> m >> e;
	for (int i = 0; i < e; ++i) {
        int a, b;
        fin >> a >> b;
		G[a].push_back(b);
	}
    int ok = 1;
	while(ok) {
		ok = 0;
		for(int i = 0; i <= n + 1; ++i)
            used[i] = false;

		for (int i = 1; i <= n; ++i)
			if (match[i] == 0)
				ok |= pairup(i);
	}

	int matching = 0;
	for (int i = 1; i <= n; ++i)
        matching += (match[i] != 0);
	fout << matching << '\n';
	for (int i = 1; i <= n; ++i)
		if (match[i] != 0)
            fout << i << ' ' << match[i] << '\n';
    return 0;
}