Cod sursa(job #1222018)

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

const int N = 1001;

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

inline int getMinHeight(int x){
    int best = n;

    for (int y : graph[x])
        if ( flux[x][y] < cap[x][y] && H[y] < best)
            best = H[y];

    return best != n ? best : -1;
}

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

    bool flag = false;

    int height = getMinHeight(x);
    if (H[x] <= height){
        H[x] = 1 + height;
        flag = true;
    }

    for (int y : graph[x])
        if ( H[x] == 1 + H[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;

            flag |= (amount != 0);
        }
    return flag;
}

int maxFlow(int S, int D){
    H[S] = n;
    for (int x : graph[S]){
        flux[S][x] += cap[S][x];
        flux[x][S] -= cap[S][x];
        E[x] = cap[S][x];
    }

    bool flag;
    do{
        flag = false;
        for (int i = 1 ; i <= n ; i++)
            if (i != D)
                flag |= pump(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;

}