Cod sursa(job #1815673)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 25 noiembrie 2016 17:07:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

const int inf = 0x3f3f3f3f;
const int nmax = 1e3 + 10;

int n, m, S, D, flow;
int dad[nmax];
vector < int > g[nmax];

int f[nmax][nmax], c[nmax][nmax];

void add_edge(int x, int y, int cost) {
    g[x].push_back(y);
    g[y].push_back(x);

    c[x][y] = cost;

    f[x][y] = f[y][x] = 0;
}

void input() {
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);

        add_edge(x, y, c);
    }
}

bool bfs(int root) {
    for (int i = 1; i <= n; ++i) dad[i] = 0;
    dad[S] = S;

    bool ret = 0;

    queue < int > q; q.push(root);
    while (q.size()) {
        int node = q.front(); q.pop();

        for (auto &it : g[node])
            if (f[node][it] < c[node][it] && !dad[it]) {
                if (it == D) ret = 1;
                else dad[it] = node, q.push(it);
            }
    }

    return ret;

}

void solve() {
    S = 1; D = n;

    while (bfs(S)) {
        for (auto &it : g[D]) {
            if (dad[it] == 0) continue;

            dad[D] = it; int add = inf;
            for (int node = D; node != S && add; node = dad[node])
                add = min(add, c[dad[node]][node] - f[dad[node]][node]);

            if (add == 0) continue;

            flow += add;
            for (int node = D; node != S; node = dad[node])
                f[dad[node]][node] += add, f[node][dad[node]] -= add;

        }
    }
}

void output() {
    printf("%d\n", flow);
}

int main() {
    freopen("maxflow.in","r",stdin);
    freopen("maxflow.out","w",stdout);

    input();
    solve();
    output();

    return 0;
}