Cod sursa(job #912397)

Utilizator veleanduAlex Velea veleandu Data 12 martie 2013 13:07:32
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>        
#include <vector>
using namespace std;

#define FORIT( it,v ) for( typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it )
#define pb push_back
#define INF 0x3f3f3f3f
#define max_n 1005

vector<int> Vertex[max_n];

int Father[max_n], Cap[max_n][max_n], Deq[max_n];
int n,m,i;
int a,b,c;
int maxflow;

bool bf(){
	int dr,mn,nod,ind;
	dr=1;
	Deq[1]=1;
	Father[1]=1;
	while( dr ){
		if( !Father[n] )
			break;
		ind = (rand()%dr) + 1;
		nod = Deq[ind];
		Deq[ind]=Deq[dr--];
		FORIT( it, Vertex[nod] ){
			if( (!Father[*it]) && Cap[nod][*it] ){
				Father[*it]=nod;
				Deq[++dr]=*it;
			}
		}
	}
	mn=INF;
	nod=n;
	if( !Father[nod] )
		return 0;
	while( nod!= 1 ){
		mn=min( mn, Cap[ Father[nod] ][ nod ] );
		nod=Father[nod];
	}
	nod=n;
	while( nod!= 1 ){
		Cap[ Father[nod] ][ nod ] -= mn;
		Cap[ nod ][ Father[nod] ] += mn;
		nod=Father[nod];
	}
	maxflow+=mn;
	return 1;
}

int main(){
	
	srand( time(NULL) );
	freopen("maxflow.in","r",stdin);
	freopen("maxflow.out","w",stdout);

	scanf("%d %d", &n, &m );
	for( i=1; i<=m; ++i ){
		scanf("%d %d %d", &a, &b, &c );
		Cap[a][b]=c;
		Vertex[a].pb(b);
		Vertex[b].pb(a);
	}
	while( bf() ){
		for( i=1; i<=n; ++i ){
			Father[i]=0;
		}
	}
	printf("%d\n", maxflow);
	return 0;
}