Cod sursa(job #1007645)

Utilizator superman_01Avramescu Cristian superman_01 Data 9 octombrie 2013 13:42:40
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>

#define MAX_SIZE 1005
#define INF 0x3f3f3f3f

using namespace std ;

ifstream in ( "maxflow.in" );
ofstream out ( "maxflow.out" ) ;
vector < int > G[MAX_SIZE];

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


int main ( void )
{
	int i , j  , x , y , cost   , node ; 
	in >> N >> M ;
	for ( i = 1 ;  i <= M ; ++i )
	{
		in >> x >> y  >> cost; 
		G[x].push_back(y);
		G[y].push_back(x);
		C[x][y]  = cost ;		
	}
	int flow = 0 , fmin ;
	for ( ; BFS() ;  )
		for ( vector < int > ::iterator it = G[N].begin() ; it != G[N].end() ; ++it )
		{
			node = *it ;
			fmin = INF ;
			if ( C[node][N] == F[node][N] || ! used[*it] )
				continue;
			TT[N] = node ;
			for( node = N ; node != 1 ; node = TT[node] )
				fmin = min ( fmin , C[TT[node]][node]  - F[TT[node]][node] );
			for ( node = N ; node != 1 ; node = TT[node] )
			{
				F[TT[node]][node] += fmin ;
				F[node][TT[node]] -= fmin;
			}
			flow += fmin ; 
		}
	out << flow << "\n" ;
	in.close();
	out.close();
	return 0;
}