Cod sursa(job #571807)

Utilizator pykhNeagoe Alexandru pykh Data 4 aprilie 2011 19:44:53
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include<cstdio>
#include<vector>
#include<bitset>
using namespace std;

#define pb push_back

const char in[]="maxflow.in";
const char out[]="maxflow.out";

const int Max_N = 1050;
const int INF = 0x3f3f3f;

vector<int>G[Max_N];
bitset<Max_N>viz;
int Q[Max_N];
int T[Max_N];
int C[Max_N][Max_N], F[Max_N][Max_N];
int N, M;

bool BF()
	{
		viz.reset();
		Q[0] = Q[1] = 1;
		viz[1] = true;
		for(int i = 1 ; i <= Q[0] ; ++i)
		{
			int nod = Q[i];
			if(nod == N) return true;
			for(unsigned j = 0 ; j < G[ nod ].size() ; ++j)
			{
				if(C[ nod ][ G[ nod ][ j ] ] == F[ nod ][ G[ nod ][ j ] ] || viz[ G[ nod ][ j ] ])continue;
				viz[ G[ nod ][ j ] ] = true;
				Q[ ++Q[ 0 ] ] = G[ nod ][ j ];
				T[ G[ nod ][ j ] ] = nod;
				if(G[nod][j] == N) return true;
			}
		}
		return false;
}

					

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