Cod sursa(job #2385125)

Utilizator MateiTrandafirMatei Trandafir MateiTrandafir Data 21 martie 2019 17:28:26
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#include <cstring>

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

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

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

int q[MAX_N], st, dr, prev[MAX_N];
bool vis[MAX_N];

bool bfs() {
    st = dr = 0;
    std::memset(vis, 0, sizeof(vis));
    q[0] = 1;
    int p, x, y;
    while (st <= dr) {
        x = q[st];
        ++st;
        if (x == n) return true;
        for (p = start[x]; p != 0; p = next[p]) {
            y = at[p];
            if (!vis[y] && f[x][y] < c[x][y]) {
                q[++dr] = y;
                prev[y] = x;
                vis[y] = true;
            }
        }
    }
    return false;
}

inline int flux() {
    int fMin = INF;
    int x, y = n;
    while (y != 1) {
        x = prev[y];
        fMin = std::min(fMin, c[x][y] - f[x][y]);
        y = x;
    }
    return fMin;
}

inline void update(int fc) {
    int x, y = n;
    while (y != 1) {
        x = prev[y];
        f[x][y] += fc;
        f[y][x] -= fc;
        y = x;
    }
}

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 (!added[x][y]) {
            add(x, y);
            added[x][y] = true;
        }
        if (!added[y][x]) {
            add(y, x);
            added[y][x] = true;
        }
    }
    int fc, ff = 0;
    while (bfs()) {
        fc = flux();
        ff += fc;
        update(fc);
    }
    out << ff;
    return 0;
}