Cod sursa(job #2440701)

Utilizator ArdeleanOficialAlexandru ArdeleanOficial Data 19 iulie 2019 02:04:23
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <cassert>
#include <vector>
#include <cstring>
#include <unordered_map>

using namespace std;

ifstream cin("maxflow.in");
ofstream cout("maxflow.out");

const int N = 1009;

vector < int > g[N];
unordered_map < int, int > cap;

namespace FLUX {
    int n, s, t;
    int dq[N];
    int dist[N];
    unordered_map < int, int > f;

    bool bfs() {
        memset(dist, 0, sizeof dist);
        int st(0), dr(-1);
        dq[++dr] = s;
        dist[s] = 1;

        while (st <= dr) {
            int x = dq[st++];

            for (int i : g[x]) {
                if (dist[i] == 0 && cap[x * (n + 1) + i] - f[x * (n + 1) + i] > 0) {
                    dist[i] = dist[x] + 1;
                    dq[++dr] = i;
                }
            }
        }

        return dist[t];
    }

    int dfs(int nod = s, int val = (int)2e9 + 7) {
        if (nod == t)
            return val;
        int ans(0);

        for (int i : g[nod]) {
            if (dist[nod] + 1 == dist[i] && cap[nod * (n + 1) + i] - f[nod * (n + 1) + i] > 0) {
                int x = dfs(i, min(cap[nod * (n + 1) + i] - f[nod * (n + 1) + i], val));
                f[nod * (n + 1) + i] += x;
                f[i * (n + 1) + nod] -= x;
                val -= x;
                ans += x;
            }
        }

        return ans;
    }

    int flux(const int &_n, const int &_s, const int &_t) {
        n = _n;
        s = _s;
        t = _t;

        int ans(0);
        while (bfs()) {
            ans += dfs();
        }

        return ans;
    }
}

int main() {
    int n, m, x, y, z;
    cin >> n >> m;

    while (m--) {
        cin >> x >> y >> z;
        cap[x * (n + 1) + y] += z;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    cout << FLUX::flux(n, 1, n);
    return 0;
}