Cod sursa(job #2698757)

Utilizator DordeDorde Matei Dorde Data 22 ianuarie 2021 22:00:53
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#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;
        while (q . size ())
            q . pop ();
        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;
            int node = x;
            while (t [node]){
                if (c [t [node]][node] < e [n])
                    e [n] = c [t [node]][node];
                node = t [node];
            }
            if (! e [n])
                continue;
            pp = true;
            r = e [n];
            flow += r;
            c [x][n] -= r;
            c [n][x] += r;
            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;
}