Pagini recente » Cod sursa (job #2222345) | Cod sursa (job #1120887) | Cod sursa (job #421456) | Cod sursa (job #2136591) | Cod sursa (job #2698747)
#include <fstream>
#include <queue>
using namespace std;
int const N = 1001 , M = 5001;
int v [2 * M] , nxt [2 * M] , vf [2 * M] , sz;
int c [N][N] , e [N] , t [N] , lst [N];
ifstream f ("maxflow.in");
ofstream g ("maxflow.out");
void add (int a , int b){
vf [++ sz] = b;
nxt [sz] = v [a];
v [a] = sz;
}
int maxflow (int n){
queue <int> q;
bool pp = true;
int ans = 0;
while (pp){
e [1] = (1 << 30);
fill (e + 2 , e + 1 + n , 0);
fill (t + 1 , t + 1 + n , 0);
lst [0] = 0;
q . push (1);
while (q . size ()){
int node = q . front ();
if (c [node][n])
lst [++ lst [0]] = node;
for(int i = v [node] ; i ; i = nxt [i]){
int y = vf [i];
if (! c [node][y] || e [y] || y == n)
continue;
e [y] = min (e [node] , c [node][y]);
t [y] = node;
q . push (y);
}
q . pop ();
}
int flow = 0;
pp = false;
for(int i = 1 ; i <= lst [0] ; ++ i){
int x = lst [i] , r = min (e [x] , c [x][n]);
e [n] = r;
if (! r)
continue;
pp = true;
flow += r;
c [x][n] -= r;
c [n][x] += r;
int node = x;
while (t [node]){
c [t [node]][node] -= r;
c [node][t [node]] += r;
node = t [node];
}
}
ans += flow;
}
return ans;
}
int main()
{
int n , m;
f >> n >> m;
for(int i = 1 ; i <= m ; ++ i){
int a , b , cost;
f >> a >> b >> cost;
add (a , b);
add (b , a);
c [a][b] = cost;
}
g << maxflow (n);
return 0;
}