Pagini recente » Cod sursa (job #68356) | Cod sursa (job #1108717) | Cod sursa (job #3033507) | Cod sursa (job #2199430) | Cod sursa (job #1511382)
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int INF = (1 << 30);
const int NMAX = 1000;
const int MMAX = 5000;
queue <int> Q;
vector <int> G[NMAX+2];
int F[NMAX+2][NMAX+2], C[NMAX+2][NMAX+2];
int viz[NMAX+2], tt[NMAX+2];
int N, M, S, D;
int BFS() {
memset( viz, 0, sizeof(viz) );
viz[ S ] = 1;
Q.push( S );
while( !Q.empty() ) {
int nod = Q.front();
Q.pop();
for( int i = 0; i < (int)G[nod].size(); ++i ) {
int x = G[nod][i];
if( viz[x] ) continue;
if( F[nod][x] < C[nod][x] ) {
viz[x] = 1;
Q.push( x );
tt[x] = nod;
}
}
}
return viz[ D ];
}
int FLUX( int start, int finish ) {
S = start;
D = finish;
int MAX_FLOW = 0;
while( BFS() ) {
for( int i = 0; i < (int)G[D].size(); ++i ) {
int fnod = G[D][i];
if( !viz[fnod] || F[fnod][D] >= C[fnod][D] ) continue;
int min_flow = C[fnod][D] - F[fnod][D];
for( int x = fnod; x != S; x = tt[x] ) {
min_flow = min( min_flow, C[ tt[x] ][ x ] - F[ tt[x] ][ x ] );
}
MAX_FLOW += min_flow;
F[ fnod ][ D ] += min_flow;
F[ D ][ fnod ] -= min_flow;
for( int x = fnod; x != S; x = tt[x] ) {
F[ tt[x] ][ x ] += min_flow;
F[ x ][ tt[x] ] -= min_flow;
}
}
}
return MAX_FLOW;
}
int main() {
in >> N >> M;
S = 1; D = N;
for( int i = 1; i <= M; ++i ) {
int x, y, cap;
in >> x >> y >> cap;
C[x][y] = cap;
G[x].push_back( y );
G[y].push_back( x );
}
out << FLUX(1, N) << '\n';
return 0;
}