Cod sursa(job #1954939)

Utilizator bullseYeIacob Sergiu bullseYe Data 5 aprilie 2017 18:58:44
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <cstdio>
#include <vector>
#include <cstring>
#define NMAX 10010

using namespace std;

vector <int> L[NMAX];
int n, m, nrMuchii;
bool viz[NMAX];
int leftSide[NMAX], rightSide[NMAX];

void citire();
void solve();
void afisare();
bool pairNodes(int);

int main() {
	citire();
	solve();
	afisare();
	return 0;
}

void citire() {
	int a, b;
	FILE*fin = fopen("cuplaj.in", "r");
	fscanf(fin, "%d %d %d\n", &n, &m, &nrMuchii);
	for (int i = 1; i <= nrMuchii; ++i) {
		fscanf(fin, "%d %d", &a, &b);
		L[a].push_back(b);
		//L[b].push_back(a);
	}
}

void solve() {
	bool stillGotAugmentingPaths = true;
	while (stillGotAugmentingPaths) {
		stillGotAugmentingPaths = false;
		memset(viz, 0, sizeof(viz));
		for (int i = 1; i <= n; ++i)
			if (!leftSide[i])
				stillGotAugmentingPaths |= pairNodes(i);
	}
}

bool pairNodes(int node) {
	if (viz[node]) return false;
	viz[node] = true;
	for (auto i: L[node])
		if (!rightSide[i]) {//nodul din dreapta nu a fost imperecheat
			rightSide[i] = node;
			leftSide[node] = i;
			return true;
		}
	
	for (auto i: L[node])
		if (pairNodes(rightSide[i])) {
			leftSide[node] = i;
			rightSide[i] = node;
			return true;
		}
	return false;
}

void afisare() {
	FILE *fout = fopen("cuplaj.out", "w");
	int nrSol = 0;
	for (int i = 1; i <= n; ++i)
		if (leftSide[i]) ++nrSol;
	
	fprintf(fout, "%d\n", nrSol);

	for (int i = 1; i <= n; ++i)
		if (leftSide[i])
			fprintf(fout, "%d %d\n", i, leftSide[i]);
	fclose(fout);
}