Cod sursa(job #623494)

Utilizator thesilverhand13FII Florea Toma Eduard thesilverhand13 Data 19 octombrie 2011 23:54:24
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
 # include <fstream>
 # include <vector>
 # include <algorithm>
 # include <queue>
 
 # define dim 1005
 # define inf 999999
 
 # define pb push_back
 
 using namespace std;
 
 ifstream f("maxflow.in");
 ofstream g("maxflow.out");
 
 int n, m;
 
 vector < int > a[ dim ];
 queue < int > q;
 
 int c[ dim ][ dim ], F[ dim ][ dim ];
 int t[ dim ], viz[ dim ];
 
 int maxflow, flow;
 
 int minim( int x, int y )
 {
	 if ( x < y )
		 return x;
	 return y;
 }
 
 void citire()
 {
	 int i, x, y, z;
	 f >> n >> m;
	 for ( i = 1 ; i <= m ; i++ )
	 {
		 f >> x >> y >> z;
		 a[ x ].pb( y );
		 a[ y ].pb( x );
		 c[ x ][ y ] = z;
	 }
 }
 
 int bf()
 {
	 int i, nod;
	 
	 q.push( 1 );
	 viz[ 1 ] = 1;
	 
	  for ( i = 1 ; i <= n ; i++ )
		 viz [ i ] = 0;
	 
	 while ( !q.empty () )
	 {
		 nod = q.front();
		 
		 if ( nod != n )
		 for ( i = 0 ; i < a[ nod ].size() ; i++ )
			 if ( viz[ a[ nod ][ i ] ] == 0 && F[ nod ][ a[ nod ][ i ] ] < c[ nod ][ a[ nod ][ i ] ] )
			 {
				 viz[ a[ nod ][ i ] ] = 1;
				 q.push( a[ nod ][ i ] );
				 t[ a[ nod ][ i ] ] = nod;
			 }
			 
			 q.pop();
	 }
	 
	 return viz[ n ];
 }
 
 void rezolva()
 {
	 int i, nod;
	 while ( bf() )
	 {
		for ( i = 0 ; i  < a[ n ].size() ; i++ )
			if( viz[ a[ n ][ i ] ] == 1 && F[ a[ n ][ i ] ][ n ] < c[ a[ n ][ i ] ][ n ] )
			{
				t[ n ] = a[ n ][ i ];
				flow = inf;
				nod = n;
				
				while( nod != 1 )
				{
					flow = minim( flow, c[ t[ nod ] ][ nod ] - F[ t[ nod ] ][ nod ] );
					nod = t[ nod ];
				}
				
				if ( flow )
				{
					nod = n;
					while ( nod != 1 )
					{
						F[ t[ nod ] ][ nod ] = F[ t[ nod ] ][ nod ] + flow;
						F[ nod ][ t[ nod ] ] = F[ nod ][ t[ nod ] ] - flow;
						nod = t[ nod ];
					}
				}
				maxflow = maxflow + flow;
			}
	 }
	g << maxflow;
 }
 
 
 int main()
 {
	 citire();
	 rezolva();
	 return 0;
 }