Cod sursa(job #3196331)

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

static int n, m, s, t, res[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 + 1, tata + n + 1, 0);
    std::fill(viz + 1, 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] && res[x][y] > 0) {
                q.push(y);
                viz[y] = true;
                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);
        res[a][b] = c;
        res[b][a] = 0;
    }

    s = 1; t = n;

    while(bfs(s)) {
        int flux = 10000000;
        int v = t;
        while(v != s) {
            flux = std::min(flux, res[tata[v]][v]);
            v = tata[v];
        }

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

        fluxmax += flux;
    }

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