Pagini recente » Cod sursa (job #1215146) | Cod sursa (job #1904874) | Cod sursa (job #1215153) | Cod sursa (job #2610575) | Cod sursa (job #2097199)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fcin("maxflow.in");
ofstream fcout("maxflow.out");
const int NLIM = 1024;
int N, M;
vector< int > graph[NLIM];
int cost[NLIM][NLIM];
int flow[NLIM][NLIM];
int back[NLIM];
int bfs[NLIM];
int main()
{
fcin >> N >> M;
for( int i = 0; i < M; ++i )
{
int x, y, c;
fcin >> x >> y >> c;
cost[x][y] = c;
graph[x].push_back( y );
graph[y].push_back( x );
}
int res = 0;
while( 1 )
{
// BFS
for( int i = 0; i <= N; ++i ){ bfs[i] = false; back[i] = 0; };
queue< int > qu;
qu.push( 1 );
while( qu.size() )
{
int nod = qu.front(); qu.pop();
if( nod == N ) continue;
for( int j = 0; j < graph[nod].size(); ++j )
{
int nnod = graph[nod][j];
if( !( bfs[nnod] ) && !( cost[nod][nnod] == flow[nod][nnod] ) )
{
qu.push( nnod );
bfs[nnod] = true;
back[nnod] = nod;
}
}
}
// if we did not reach the destination => no more augmenting paths
if( !bfs[N] ) break;
for( int i = 0; i < graph[N].size(); ++i )
{
int nod = graph[N][i];
if( ( cost[nod][N] == flow[nod][N] ) || !bfs[nod] ) continue;
back[N] = nod;
int fmin = INT_MAX;
for( nod = N; nod != 1; nod = back[nod] )
fmin = min( fmin, cost[back[nod]][nod] - flow[back[nod]][nod] );
if( fmin == 0 ) continue; // the rest of the loop wouldn't do anything
for( nod = N; nod != 1; nod = back[nod] )
{
flow[back[nod]][nod] += fmin;
//flow[nod][back[nod]] -= fmin;
}
res += fmin;
}
}
fcout << res << "\n";
}