Cod sursa(job #2013555)

Utilizator mihai.alphamihai craciun mihai.alpha Data 21 august 2017 18:37:45
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <vector>
#include <string.h>

using namespace std;

FILE *fin = fopen("cuplaj.in", "r");
FILE *fout = fopen("cuplaj.out", "w");

#define BUF 1 << 17
int pos = BUF;
char buf[BUF];

inline char next() {
	if (pos == BUF)
		fread(buf, 1, BUF, fin), pos = 0;
	return buf[pos++];
}

inline int read() {
	int x = 0;
	char ch = next();
	while (!isdigit(ch))
		ch = next();
	while (isdigit(ch))
		x = x * 10 + ch - '0', ch = next();
	return x;
}

#define MAX_N 10001

int N, M, E;
vector <int> G[MAX_N];

int u[MAX_N], v[MAX_N];
bool viz[MAX_N];

bool pairs(int nod) {
	if (viz[nod])
		return 0;
	viz[nod] = 1;
	for (unsigned int i = 0; i < G[nod].size(); i++) {
		if (v[G[nod][i]] == 0) {
			u[nod] = G[nod][i];
			v[G[nod][i]] = nod;
			return 1;
		}
	}
	for (unsigned int i = 0; i < G[nod].size(); i++) {
		if (pairs(v[G[nod][i]])) {
			u[nod] = G[nod][i];
			v[G[nod][i]] = nod;
			return 1;
		}
	}
	return 0;
}

int main() {
	N = read(), M = read(), E = read();
	for (int i = 0; i < E; i++) {
		int x, y;
		x = read(), y = read();
		G[x].push_back(y);
	}
	bool ok = 1;
	while (ok) {
		ok = 0;
		memset(viz, 0, sizeof(viz));
		for (int i = 1; i <= N; i++)
			if (!u[i])
				if (pairs(i))
					ok = 1;
	}
	int nr = 0;
	for (int i = 1; i <= N; i++)
		if (u[i])
			nr++;
	fprintf(fout, "%d\n", nr);
	for (int i = 1; i <= N; i++)
		if (u[i])
			fprintf(fout, "%d %d\n", i, u[i]);
	fclose(fin);
	fclose(fout);
	return 0;
}