Cod sursa(job #1222017)

Utilizator mihai995mihai995 mihai995 Data 21 august 2014 22:00:52
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
using namespace std;

const int N = 1001, inf = 0x3f3f3f3f;

int cap[N][N], flux[N][N], H[N], E[N], n;
vector<int> graph[N];

bool pump(int x, int y){
    int amount = min(E[x], cap[x][y] - flux[x][y]);

    flux[x][y] += amount;
    flux[y][x] -= amount;

    E[x] -= amount;
    E[y] += amount;

    return amount != 0;
}

bool improve(int x){
    if ( !E[x] ) return false;

    bool flag = false;
    int best = 1;

    for (int y : graph[x])
        if ( H[x] == 1 + H[y] )
            flag |= pump(x, y);
        else if ( H[y] < H[best] && flux[x][y] < cap[x][y])
            best = y;

    if (best != 1 && E[x] && H[x] <= H[best]){
        H[x] = 1 + H[best];
        flag = pump(x, best);
    }

    return flag;
}

int maxFlow(int S, int D){
    E[S] = inf;
    H[S] = n;

    for (int x : graph[S])
        pump(S, x);

    bool flag;
    do{
        flag = false;
        for (int i = 1 ; i <= n ; i++)
            if (i != D)
                flag |= improve(i);
    } while (flag);

    return E[D];
}

int main(){
    ifstream in("maxflow.in");

    int m, x, y, c;

    in >> n >> m;
    while (m--){
        in >> x >> y >> c;

        graph[x].push_back(y);
        graph[y].push_back(x);

        cap[x][y] = c;
    }

    in.close();

    ofstream out("maxflow.out");
    out << maxFlow(1, n) << '\n';
    out.close();

    return 0;

}