Pagini recente » Cod sursa (job #2009203) | Cod sursa (job #983478) | Cod sursa (job #1755652) | Cod sursa (job #2815480) | Cod sursa (job #2017775)
# include <iostream>
# include <fstream>
# include <algorithm>
# include <vector>
# include <deque>
# include <cstring>
using namespace std;
const int MAX_N = 1000;
int flow[1 + MAX_N][1 + MAX_N];
int p[1 + MAX_N];
vector<int> bords[1 + MAX_N];
bool bfs( int s, int d ) {
memset( p, 0, sizeof( p ) );
deque<int> q;
q.push_back( s );
while ( q.size() ) {
int u = q.front();
q.pop_front();
if ( u == d )
return true;
else {
for ( int v : bords[u] )
if ( flow[u][v] > 0 && !p[v] ) {
p[v] = u;
q.push_back( v );
}
}
}
return false;
}
int randInt( int n ) {
return rand() % n;
}
int main() {
srand( time( NULL ) );
ifstream fin( "maxflow.in" );
ofstream fout( "maxflow.out" );
int n, m;
fin >> n >> m;
for ( int i = 0; i < m; i ++ ) {
int x, y, c;
fin >> x >> y >> c;
flow[x][y] = c;
if ( !flow[y][x] ) {
bords[x].push_back( y );
bords[y].push_back( x );
}
}
for ( int i = 1; i <= n; i ++ )
random_shuffle( bords[i].begin(), bords[i].end(), randInt );
int total_f = 0;
while ( bfs( 1, n ) ) {
int f = 1e9;
for ( int u = n; u != 1; u = p[u] )
f = min( f, flow[p[u]][u] );
total_f += f;
for ( int u = n; u != 1; u = p[u] ) {
flow[p[u]][u] -= f;
flow[u][p[u]] += f;
}
}
fout << total_f;
return 0;
}