Cod sursa(job #457877)

Utilizator mihaif3feier mihai mihaif3 Data 21 mai 2010 21:53:01
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <stdio.h>
#include <vector.h>

#define N 1000
//---------------------
int vis[N], par[N], bf[N], reach[N];
int cost[N][N], used[N][N];
vector<int> adj[N];
int n,m, flux, nreach;
//---------------------
void read()
{
	FILE *f = fopen("maxflow.in","r");
	fscanf(f,"%d %d",&n,&m);
	for(int i=0; i<m; i++)
	{
		int a,b,c;
		fscanf(f,"%d %d %d",&a,&b,&c);
		used[--a][--b] = 0;
		used[b][a] = c;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}
}
//---------------------
int bfs()
{
	bf[0] = 0;
	vis[0] = 1;
	int i,s,d,a,v;
	memset(vis,0,n*sizeof(int));
	nreach = 0;
	for(s=0, d=1; s<d; s++)
	{
		a = bf[s];
		for(i=0; i<adj[a].size(); i++)
		{
			v = adj[a][i];
			if(vis[v] == 0 && used[v][a] > 0)
			{
				if(v == n-1)
					reach[nreach++] = v;
				vis[v] = 1;
				par[v] = a;
				bf[d++] = v;
			}
		}
	}
	return (nreach != 0);
}
//---------------------
void solve()
{
	flux = 0;
	while(bfs())
	{
		for(int i=0; i<nreach; i++)
		{
			int cflux = 1<<20;
			for(int j=reach[i]; j != 0; j = par[j])
				if(used[j][par[j]] < cflux)
					cflux = used[j][par[j]];
			for(int j=reach[i]; j != 0; j = par[j])
			{
				used[par[j]][j] += cflux;
				used[j][par[j]] -= cflux;
			}
			flux += cflux;
		}
	}
	FILE *f = fopen("maxflow.out","w");
	fprintf(f,"%d",flux);
	fclose(f);
}
//---------------------
int main()
{
	read();
	solve();
	return 0;
}