Cod sursa(job #623497)

Utilizator thesilverhand13FII Florea Toma Eduard thesilverhand13 Data 20 octombrie 2011 00:29:34
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 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;
	 
	 for ( i = 1 ; i <= n ; i++ )
		 viz[ i ] = 0;
	 
	 q.push( 1 );
	 viz[ 1 ] = 1;
	 
	 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 ] ] )
			 {
				 q.push( a[ nod ][ i ] );
				 viz[ a[ nod ][ i ] ] = 1;
				 t[ a[ nod ][ i ] ] = nod;
			 }
			 q.pop();
	 }
	 
	 return viz[ n ];
 }
 
 void rezolva()
 {
	 int nod, i;
	 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 = min( flow, c[ t[ nod ] ][ nod ] - F[ t[ nod ] ][ nod ] );
					 nod = t[ nod ];
				 }
				 
				 nod = n;
				 if ( flow )
				 {
					 nod = n;
				 while ( nod != 1 )
				   {
					 F[ t[ nod ] ][ nod ] += flow;
					 F[ nod ][ t[ nod ] ] -= flow;
					 nod = t[ nod ];
				   }
				 }
				 maxflow = maxflow + flow;
			 }
	 }
	 g << maxflow;
 }
 
 int main()
 {
	 citire();
	 rezolva();
	 return 0;
 }