Cod sursa(job #626825)

Utilizator sebii_cSebastian Claici sebii_c Data 28 octombrie 2011 13:57:52
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator c Status done
Runda Arhiva educationala Marime 1.87 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NMAX 10010

struct graf {
    int node, cap, flow;
    struct graf *next;
    struct graf *aft;
};

struct graf *A[NMAX];
struct graf *from[NMAX];
int viz[NMAX], Q[NMAX];
int N, M, E, source, sink, head, tail;

void add(int i, int j)
{
    struct graf *new = malloc(sizeof(struct graf));
    struct graf *nxt = malloc(sizeof(struct graf));
    new->node = j;
    nxt->node = i;
    new->aft = nxt;
    nxt->aft = new;
    new->next = A[i];
    nxt->next = A[j];
    A[i] = new;
    A[j] = nxt;
    new->cap = 1, new->flow = nxt->flow = nxt->cap = 0;
}

void read()
{
    int x, y, i;
    scanf("%d %d %d", &N, &M, &E);
    for (i=1; i<=E; ++i) {
	scanf("%d %d", &x, &y);
	add(x, y+N);
    }
    source = 0;
    for (i=1; i<=N; ++i) 
	add(source, i);
    sink = N+M+1;
    for (i=N+1; i<=N+M; ++i)
	add(i, sink);
}

int BFS(int source, int sink)
{
    struct graf *node;
    memset(viz, 0, sizeof(viz));
    head = tail = 0;
    Q[head++] = source;
    viz[source] = 1;
    while (tail < head) {
	node = A[Q[tail++]];
	while (node) {
	    if ((node->cap - node->flow) > 0 && !viz[node->node]) {
		viz[node->node] = 1;
		Q[head++] = node->node;
		from[node->node] = node;
		if (node->node == sink) {
		    for (node = from[sink]; node; node = from[node->aft->node]) {
			++node->flow;
			--node->aft->flow;
		    }
		    return 1;
		}
	    }
	    node = node->next;
	}
    }
    return 0;
}

int main()
{
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);
    int i;
    struct graf *it;
    int result = 0;
    read();
    while (BFS(source, sink))
	++result;
    printf("%d\n", result);
    for (i=1; i<=N; ++i) 
	for (it = A[i]; it; it = it->next) 
	    if (it->flow == 1)
		printf("%d %d\n", i, it->node-N);
    return 0;
}