Cod sursa(job #2961700)

Utilizator TeoDiDiaconescu Teodora TeoDi Data 6 ianuarie 2023 21:18:07
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
#define oo 1e9
int n;

using namespace std;

int Dinic(int s, int t, vector<vector<int>> &cap, vector<vector<int>> &flow) {
    vector<int> level(n), ptr(n);
    function<bool(int)> bfs = [&](int s) {
        fill(level.begin(), level.end(), -1);
        queue<int> q;
        q.push(s);
        level[s] = 0;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (int v = 0; v < n; v++) {
                if (level[v] == -1 && cap[u][v] - flow[u][v] > 0) {
                    level[v] = level[u] + 1;
                    q.push(v);
                }
            }
        }
        return level[t] != -1;
    };
    function<int(int, int)> dfs = [&](int u, int pushed) {
        if (pushed == 0) return 0;
        if (u == t) return pushed;
        for (int &cid = ptr[u]; cid < n; cid++) {
            int v = cid;
            if (level[v] == level[u] + 1 && cap[u][v] - flow[u][v] > 0) {
                int tr = dfs(v, min(pushed, cap[u][v] - flow[u][v]));
                if (tr == 0) continue;
                flow[u][v] += tr;
                flow[v][u] -= tr;
                return tr;
            }
        }
        return 0;
    };
    int f = 0;
    while (bfs(s)) {
        fill(ptr.begin(), ptr.end(), 0);
        while (int pushed = dfs(s, oo)) {
            f += pushed;
        }
    }
    return f;
}

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int main() {
    int m;
    fin >> n >> m;
    vector<vector<int>> cap(n, vector<int>(n));
    vector<vector<int>> flow(n, vector<int>(n));
    for(int i = 0; i < m; i++){
        int x, y, c;
        fin >> x >> y >> c;
        x--; y--;
        cap[x][y] += c;

    }
    fout<<Dinic(0, n - 1, cap, flow);
    return 0;
}