Cod sursa(job #1920935)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 10 martie 2017 10:42:43
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

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

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

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

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

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

        add_edge(x, y, z);
    }
}

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

    queue < int > q; q.push(S); dad[S] = 0;
    while (q.size()) {
        int node = q.front(); q.pop();

        for (auto &it: g[node]) {
            if (f[node][it] >= c[node][it]) continue;
            if (dad[it] != -1) continue;

            if (it == D) ok = 1;
            else dad[it] = node, q.push(it);
        }
    }

    return ok;
}

void maxflow() {
    S = 1; D = n;
    while (bfs()) {
        for (auto &it: g[D]) {
            if (dad[it] == -1) continue;

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

            if (best == 0) continue;

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

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

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

    input();
    maxflow();
    output();

    return 0;
}