Cod sursa(job #555675)

Utilizator Addy.Adrian Draghici Addy. Data 15 martie 2011 18:09:55
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <cstdio>
#include <list>

using namespace std;

#define NMAX 10050

int L[NMAX], R[NMAX], viz[NMAX], sol, n, m;
list <int> G[NMAX];

bool pair_up (int);
void citire (), cuplaj (), afisare ();

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

void citire () {
	
	freopen ("cuplaj.in", "r", stdin);
	
	int p, i, x, y;
	
	scanf ("%d %d %d", &n, &m, &p);
	
	for (i = 1; i <= p; i++) {
		scanf ("%d %d", &x, &y);
		G[x].push_back (y);
	}
}

bool pair_up (int nod) {
	
	if (viz[nod]) return 0;
	
	list <int>::iterator it;
	
	viz[nod] = 1;
	
	for (it = G[nod].begin (); it != G[nod].end (); it++)
		if (!R[*it]) {
			L[nod] = *it;
			R[*it] = nod;
			return 1;
		}
	
	for (it = G[nod].begin (); it != G[nod].end (); it++)
		if (pair_up (R[*it])) {
			L[nod] = *it;
			R[*it] = nod;
			return 1;
		}
	
	return 0;
}

void cuplaj () {
	
	bool ok;
	int i;
	
	for (ok = 0; !ok; ) {
		ok = 1;
		memset (viz, 0, sizeof (viz));
		
		for (i = 1; i <= n; i++)
			if (!L[i])
				if (pair_up (i)) ok = 0;
	}
	
	for (i = 1; i <= n; i++)
		if (L[i]) sol++;
}

void afisare () {
	
	freopen ("cuplaj.out", "w", stdout);
	
	printf ("%d\n", sol);
	
	for (int i = 1; i <= n; i++)
		if (L[i]) printf ("%d %d\n", i, L[i]);
}