Cod sursa(job #1217516)

Utilizator pulseOvidiu Giorgi pulse Data 7 august 2014 16:52:16
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
#define INF 0x3f3f3f3f

using namespace std;

const int MAXN = 1005;
int N, M, C[MAXN][MAXN], F[MAXN][MAXN], T[MAXN];
vector <int> G[MAXN];
queue <int> Q;
bool Used[MAXN];

int BFS()
{
	memset(Used, 0, sizeof(Used));
	Q.push(1);
	Used[1] = true;
	while (!Q.empty())
	{
		int node = Q.front(); Q.pop();
		if (node == N) continue;
		for (vector <int> :: iterator it = G[node].begin(); it != G[node].end(); ++it)
		{
			int V = *it;
			if (C[node][V] == F[node][V] || Used[V]) continue;
			Used[V] = true;
			Q.push(V);
			T[V] = node;
		}
	}
	return Used[N];
}

int main()
{
	freopen("maxflow.in",  "r", stdin);
	freopen("maxflow.out", "w", stdout);
	int flow, fmin, node, x, y, z;
	scanf("%d %d", &N, &M);
	for (int i = 1; i <= M; ++i)
	{
		scanf("%d %d %d", &x, &y, &z);
		G[x].push_back(y);
		G[y].push_back(x);
		C[x][y] += z;
	}
	for (flow = 0; BFS(); )
	{
		for (int i = 0; i < G[N].size(); ++i)
		{
			node = G[N][i];
			if (F[node][N] == C[node][N] || !Used[node]) continue;
			T[N] = node;
			fmin = INF;
			for (node = N; node != 1; node = T[node])
				fmin = min(fmin, C[T[node]][node] - F[T[node]][node]);
			if (fmin == 0) continue;
			for (node = N; node != 1; node = T[node])
			{
				F[T[node]][node] += fmin;
				F[node][T[node]] -= fmin;
			}
			flow += fmin;
		}
	}
	printf("%d\n", flow);
	return 0;
}