Cod sursa(job #743159)

Utilizator Stefex09Stefan Teodorescu Stefex09 Data 3 mai 2012 16:14:15
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include<cstdio>
#include<vector>

using namespace std;

const int maxn = 1 << 10;
const int inf = 1 << 30;

int c[maxn][maxn], f[maxn][maxn], tt[maxn], m, n, cd[maxn], viz[maxn];

vector <int> graf[maxn];

int BF()
{
	int i, j, nod, V;
	
	cd[0] = 1;
	cd[1] = 1;
	memset(viz, 0, sizeof(viz));
	viz[1] = 1;
	
	for(i=1; i<=cd[0]; ++i){
		nod = cd[i];
		if(nod == n)
			continue;
		
		for(j=0; j<graf[nod].size(); ++j){
			V = graf[nod][j];
			if (c[nod][V] == f[nod][V] || viz[V])
				continue;
			viz[V] = 1;
			cd[ ++cd[0] ] = V;
			tt[V] = nod;
		}
	}
	
	return viz[n];
}

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	
	int i, flow, fmin, x, y, z, nod;
	
	scanf("%d %d", &n, &m);
	
	for(i=1; i<=m; ++i){
		scanf("%d %d %d", &x, &y, &z);
		c[x][y] += z;
		graf[x].push_back(y);
		graf[y].push_back(x);
	}
	
	for(flow = 0; BF();)
		for(i=0; i<graf[n].size(); ++i){
			nod = graf[n][i];
			if (f[nod][n] == c[nod][n] || !viz[nod]) 
				continue;
			tt[n] = nod;
		
			fmin = inf;
			for(nod=n; nod != 1; nod = tt[nod])
				fmin = min(fmin, c[ tt[nod] ][nod] - f[ tt[nod] ][nod]);
		
			if(fmin == 0)
				continue;
		
			for(nod=n; nod != 1; nod = tt[nod]){
				f[ tt[nod] ][nod] += fmin;
				f[nod][ tt[nod] ] -= fmin;
			}
		
			flow += fmin;
		}
	
		printf("%d", flow);
		
		return 0;
}