Pagini recente » Cod sursa (job #1361428) | Cod sursa (job #932872) | Cod sursa (job #418161) | Cod sursa (job #735132) | Cod sursa (job #1368339)
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#include <fstream>
using namespace std;
//ifstream in("maxflow.in");
//ofstream out("maxflow.out");
const int MAXN = 1000, INF = 2000000000;
vector <int> G[MAXN+1];
int N, M, C[MAXN+1][MAXN+1], T[MAXN+1], viz[MAXN+1];
void citire()
{
scanf("%d %d",&N,&M);
//in>>N>>M;
for(int i = 1; i <= M; i++)
{
int x, y, z; scanf("%d %d %d",&x,&y, &z);
//in>>x>>y>>z;
G[ x ].push_back( y ); G[ y ].push_back( x );
C[ x ][ y ] += z;
}
}
void setViz0()
{
for(int i = 1; i <= N; i++)
viz[ i ] = 0;
}
bool findAugPath()
{
setViz0();
queue <int> c; c.push( 1 ); viz[ 1 ] = 1;
while( c.empty() == false )
{
int nc = c.front(); c.pop(); viz [ nc ] = 1;
for(int i = 0; i < G[ nc ].size(); i++)
{
int next = G[ nc ][ i ];
if( viz[ next ] == 0 && ( C[ nc ][ next ] > 0 ) )
{
T[ next ] = nc; c.push( next ); viz[ next ] = 1;
if( next == N )
return true;
}
}
}
return false;
}
int minOnAugPath()
{
int nod = N, minF = INF;
while( nod != 1 )
{
//cout<<nod<<' ';
minF = min( minF, C[ T[ nod ] ][ nod ] );
nod = T[ nod ];
}
//cout<<1<<' ';
//cout<<endl;
return minF;
}
void updateFlowOnAugPath(int f)
{
int nod = N;
while( nod != 1 )
{
C[ T[ nod ] ][ nod ] -= f;
C[ nod ][ T[ nod ] ] += f;
nod = T[ nod ];
}
}
int maxFlow = 0;
void findMaxFlow()
{
while( findAugPath() == true )
for(int i = 0; i < G[ N ].size(); i++)
{
int nod = G[ N ][ i ];
if( viz[ nod ] == 1 && C[ nod ][ N ] > 0 )
{
T[ N ] = nod;
int f = minOnAugPath();
updateFlowOnAugPath( f );
maxFlow += f;
}
}
}
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
citire();
findMaxFlow();
cout<<maxFlow;
return 0;
}