Cod sursa(job #3196336)

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

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

static auto bfs(const int& s) -> bool {
    std::fill(tata, tata + n + 1, 0);
    std::fill(viz, viz + n + 1, 0);

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

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

        for(auto&& y : adj[x]) {
            if(!viz[y] && cap[x][y] > flx[x][y]) {
                q.push(y);
                viz[y] = 1;
                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;
}