Cod sursa(job #639176)

Utilizator JBaccountCatalin JBaccount Data 22 noiembrie 2011 17:45:19
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#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];
		if (node == N) break;
		++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]) continue;
			queue[++right] = nnode;
			used[nnode] = 1;
			fat[nnode] = node;
		}	
	}	
	
	if (!used[N]) return 0;
	
	for (vector<int>::iterator it = G[N].begin(); it != G[N].end(); ++it)
	{
		int cnode = *it;
		
		if (!used[cnode]) continue;
		if (CAP[cnode][N] == FLOW[cnode][N]) continue;
		
		int node = N, flowadd = inf;
		fat[N] = cnode;
		
		while (fat[node])
		{
			int nnode = fat[node];
			flowadd = min(flowadd, CAP[nnode][node] - FLOW[nnode][node]);
			if (!flowadd) break;
			node = nnode;
		}	
		
		if (!flowadd) continue;
		
		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;
}