Cod sursa(job #664124)

Utilizator eukristianCristian L. eukristian Data 19 ianuarie 2012 18:03:35
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <cstdio>

#define MAX_SIZE 10001
#define NIL 0
#define INF 0x7fffffff
struct node {
	int key;
	node *next;
};

node *graph[MAX_SIZE];
int n, m, e;
int pair[MAX_SIZE << 1], dist[MAX_SIZE];


void read();
void add(int n1, int n2);

bool bfs();
bool dfs(int nd);

int main()
{
	read();
	int matching = 0;
	
	while (bfs())
	{
		for (int i = 1 ; i <= n ; ++i)
		{
			if (pair[i] == NIL)
				if (dfs(i))
					matching++;
		}
	}
	
	printf("%d\n", matching);
	
	for (int i = 1; i <= n ; ++i)
		if (pair[i])
			printf("%d %d\n", i, pair[i] - n);
	
	return 0;
}

void read()
{
	freopen("cuplaj.in", "r", stdin);
	freopen("cuplaj.out","w",stdout);
	
	scanf("%d%d%d", &n, &m, &e);
	for (int i = 1 ; i <= e ; ++i)
	{
		int n1, n2;
		scanf("%d%d", &n1, &n2);
		add(n1, n2);
	}
}

void add(int n1, int n2)
{
	node *q = new node;
	q->key = n2;
	q->next = graph[n1];
	graph[n1] = q;	
	
	q = new node;
	q->key = n1;
	q->next = graph[n2];
	graph[n2] = q;
}

bool bfs()
{
	int queue[MAX_SIZE], left = 0, right = -1;
	for (int i = 1 ; i <= n ; ++i)
		if (pair[i] == NIL)
		{
			dist[i] = 0;
			queue[++right] = i;
		}
		else
			dist[i] = INF;
	dist[NIL] = INF;
	
	while (left <= right)
	{
		int nd = queue[left++];
		node *q = graph[nd];
		
		while (q)
		{
			if (dist[pair[q->key]] == INF)
			{
				dist[pair[q->key]] = dist[nd] + 1;
				queue[++right] = pair[q->key];
			}
			q = q->next;
		}
	}
	
	return dist[NIL] != INF;
}

bool dfs(int nd)
{
	if (nd != NIL)
	{
		node *q = graph[nd];
		
		while (q)
		{
			if (dist[pair[q->key]] == dist[nd] + 1)
				if (dfs(pair[q->key]))
				{
					pair[nd] = q->key;
					pair[q->key] = nd;
					return true;
				}
			
			q = q->next;
		}
		
		dist[nd] = INF;
		return false;
	}
	return true;
}