Cod sursa(job #617536)

Utilizator root/boot/vmlinuz root Data 14 octombrie 2011 23:57:49
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <stdio.h>
#include <vector>
#include <string.h>

using namespace std;

#define MN (1000)

int C[MN][MN]; // capacity
int F[MN][MN]; // flow
int P[MN]; // parent
vector<int> G[MN]; // graph (adjacency list)
int N, M;

int bfs()
{
	// Source is 0, Sink is N-1
	int queue[MN+1] = {1, 0}, q;
	int seen[MN] = {1}; // visited
	int i;

	for(q = 1; q <= queue[0]; ++q) {
		int a = queue[q]; // current node
		int b; // neighbour
		//printf("Treating %d\n", a);
		for(i = 0; i < G[a].size(); ++i) {
			b = G[a][i];
			if(seen[b] || F[a][b] >= C[a][b])
				continue;
			//printf("Added %d\n to the queue.\n", b);
			seen[b] = 1;
			queue[++queue[0]] = b;
			P[b] = a;
			if(b == N-1) // Did we reach the sink?
				return 1;
		}
	}

	return 0;
}

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	
	int i;
	int flow; // total flow
	int faug; // maximum flow allowed on the augmenting path

	scanf("%d %d", &N, &M);
	for(i = 0; i < M; ++i) {
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		--a; --b;
		G[a].push_back(b);
		G[b].push_back(a); // construct the residual graph
		C[a][b] = c;
		// Of course, C[b][a] = 0
	}

	for(flow = 0; bfs(); flow += faug) {
		memset(&faug, 0x3f, sizeof(faug));
		for(i = N-1; i; i = P[i])
			faug = min(faug, C[P[i]][i]-F[P[i]][i]);
		for(i = N-1; i; i = P[i]) {
			F[P[i]][i] += faug;
			F[i][P[i]] -= faug;
		}
		//printf("faug %d\n", faug);
	}

	printf("%d\n", flow);

	return 0;
}