Cod sursa(job #1545548)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 6 decembrie 2015 20:40:28
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <stdio.h>
#include <string.h>
#include <vector>
#define MAX 10005
using namespace std;

int n, m, e, x, y, pair1[MAX], pair2[MAX];
bool viz1[MAX], viz2[MAX];
vector<int> l[MAX];

bool match(int i){
	if(viz1[i])
		return 0;
	else{
		viz1[i] = 1;
		for(int j = 0; j < l[i].size(); j++)
			if(!pair2[l[i][j]]){
				pair1[i] = l[i][j];
				pair2[l[i][j]] = i;
				return 1;
			}

		for(int j = 0; j < l[i].size(); j++)
			if(match(pair2[l[i][j]])){
				pair1[i] = l[i][j];
				pair2[l[i][j]] = i;
				return 1;
			}
	}
}

int main(){
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out", "r", stdin);
	scanf("%d%d%d", &n, &m, &e);
	for(int i = 0; i < e; i++){
		scanf("%d%d", &x, &y);
		l[x].push_back(y);
	}

	bool stop = 1;
	while(stop){
		stop = 0;
		memset(viz1 + 1, 0, n);
		memset(viz2 + 1, 0, m);
		for(int i = 1; i <= n; i++)
			if(!pair1[i]){
				int x = match(i);
				if(x)
					stop = 1;
			}
	}

	int nr = 0;
	for(int i = 1; i <= n; i++)
		if(pair1[i])
			nr++;
	printf("%d\n", nr);
	for(int i = 1; i <= n; i++)
		if(pair1[i])
			printf("%d %d\n", i, pair1[i]);
	return 0;
}