Cod sursa(job #3196342)

Utilizator npc3233npc npc npc3233 Data 23 ianuarie 2024 18:29:58
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

#pragma GCC optimize("Ofast")

static int n, m, s, t, cap[1001][1001], flx[1001][1001], tata[1001] = {0}, fluxmax;
static std::list<int> adj[1001];

static auto bfs(const int& s) -> bool {
    std::memset(tata, 0, sizeof(int) * 1001);

    std::queue<int> q = {};
    q.push(s); tata[s] = s;

    while(!q.empty()) {
        int x = q.front();
        q.pop();

        for(auto&& y : adj[x]) {
            if(!tata[y] && cap[x][y] > flx[x][y]) {
                q.push(y);
                tata[y] = x;
                if(y == t) return true;
            }
        }
    }

    return false;
}

auto main() -> int {
    std::ios_base::sync_with_stdio(false);
    std::cout.tie(nullptr);
    std::cin.tie(nullptr);

    std::freopen("maxflow.in", "r", stdin);
    std::freopen("maxflow.out", "w", stdout);

    std::cin >> n >> m;
    for(int i = 1, a, b, c; i <= m; ++i) {
        std::cin >> a >> b >> c;
        adj[a].push_back(b);
        adj[b].push_back(a);
        cap[a][b] = c;
    }

    s = 1; t = n;

    while(bfs(s)) {
        int flux = 1e9;
        int v = t;
        while(v != s) {
            flux = std::min(flux, cap[tata[v]][v] - flx[tata[v]][v]);
            v = tata[v];
        }

        v = t;
        while(v != s) {
            flx[tata[v]][v] += flux;
            flx[v][tata[v]] -= flux;
            v = tata[v];
        }

        fluxmax += flux;
    }

    std::cout << fluxmax << std::endl;
    return 0;
}