Cod sursa(job #639160)

Utilizator JBaccountCatalin JBaccount Data 22 noiembrie 2011 17:20:00
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>

using namespace std;

#define NM 1005
#define PB push_back
#define inf 1000000000

int CAP[NM][NM], FLOW[NM][NM], flow, N, M;
vector <int> G[NM];

int bfs()
{
	int used[NM], queue[NM], fat[NM], left = 0, right = -1;
	memset (used, 0, sizeof(used));
	queue[++right] = 1;
	used[1] = 1;
	fat[1] = 0;
	
	while (left <= right)
	{
		int node = queue[left];
		++left;
		for (vector<int>::iterator it = G[node].begin(); it != G[node].end(); ++it)
		{
			int nnode = *it;
			if (used[nnode]) continue;
			if (CAP[node][nnode] - FLOW[node][nnode] <= 0) continue;
			queue[++right] = nnode;
			used[nnode] = 1;
			fat[nnode] = node;
		}	
	}	
	
	if (!used[N]) return 0;
	int node = N, flowadd = inf;
	while (fat[node])
	{
		int nnode = fat[node];
		flowadd = min(flowadd, CAP[nnode][node] - FLOW[nnode][node]);
		node = nnode;
	}	
	
	flow += flowadd;
	node = N;
	while (fat[node])
	{
		int nnode = fat[node];
		FLOW[nnode][node] += flowadd;
		FLOW[node][nnode] -= flowadd;
		node = nnode;
	}	
	
	return 1;
}

int main()
{
	freopen ("maxflow.in", "r", stdin);
	freopen ("maxflow.out", "w", stdout);
	
	scanf ("%d %d", &N, &M);
	
	for (int i = 1; i <= M; ++i)
	{
		int a, b, c;
		scanf ("%d %d %d", &a, &b, &c);
		
		G[a].PB(b);
		G[b].PB(a);
		CAP[a][b] += c;
	}	
	
	while (bfs());
	
	printf ("%d", flow);
	
	return 0;
}