Cod sursa(job #2385150)

Utilizator MateiTrandafirMatei Trandafir MateiTrandafir Data 21 martie 2019 17:51:56
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <fstream>
#include <cstring>

constexpr int MAX_N = 1001, MAX_M = 10001, INF = 0x7fffffff;

int n, m;
int list[MAX_N], start[MAX_N], next[MAX_M], at[MAX_M], count;
int c[MAX_N][MAX_N], f[MAX_N][MAX_N];
bool a[MAX_N][MAX_N];

inline void add(int from, int to) {
    ++count;
    at[count] = to;
    next[count] = list[from];
    list[from] = count;
}

int level[MAX_N], q[MAX_N], st, dr;

inline bool bfs() {
    std::memset(level, 0xff, sizeof(level));
    st = dr = 0;
    q[0] = 1;
    level[1] = 0;
    int x, y;
    while (st <= dr) {
        x = q[st++];
        for (int p = list[x]; p != 0; p = next[p]) {
            y = at[p];
            if (level[y] == -1 && f[x][y] < c[x][y]) {
                level[y] = level[x] + 1;
                q[++dr] = y;
            }
        }
    }
    return level[n] != -1;
}

inline int flux(int x, int fMin) {
    if (x == n) return fMin;
    int y, fMin2;
    for (; start[x] != 0; start[x] = next[start[x]]) {
        y = at[start[x]];
        if (f[x][y] < c[x][y] && level[y] == level[x] + 1) {
            fMin2 = std::min(fMin, c[x][y] - f[x][y]);
            fMin2 = flux(y, fMin2);
            if (fMin2 > 0) {
                f[x][y] += fMin2;
                f[y][x] -= fMin2;
                return fMin2;
            }
        }
    }
    return 0;
}

int main() {
    std::ifstream in("maxflow.in");
    std::ofstream out("maxflow.out");
    int i, x, y, z;
    in >> n >> m;
    for (i = 0; i < m; ++i) {
        in >> x >> y >> z;
        c[x][y] = z;
        if (!a[x][y]) {
            add(x, y);
            a[x][y] = true;
        }
        if (!a[y][x]) {
            add(y, x);
            a[y][x] = true;
        }
    }
    int ff = 0, fc;
    while (bfs()) {
        for (i = 1; i <= n; ++i) start[i] = list[i];
        fc = flux(1, INF);
        while (fc > 0) {
            ff += fc;
            fc = flux(1, INF);
        }
    }
    out << ff;
    return 0;
}