Cod sursa(job #3298820)

Utilizator HandoMihnea-Vicentiu Hando Data 2 iunie 2025 10:08:44
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <queue>
#include <vector>
#include <iostream>

struct EdmonsKarp {
    int V;
    std::vector <std::basic_string <int>> G; 
    std::vector <std::vector <int>> c;

    EdmonsKarp(int V) : V(V) {
        G.assign(V, std::basic_string<int>());
        c.assign(V, std::vector<int>(V, 0));
    }

    void addEdge(int u, int v, int cap) {
        G[u].push_back(v);
        G[v].push_back(u);
        c[u][v] += cap; 
    }

    int bfs(int s, int t, std::vector <int>& par) {
        std::fill(par.begin(), par.end(), -1);
        par[s] = -2;

        std::queue <std::pair <int, int>> q;
        q.emplace(s, std::numeric_limits<int>::max());

        while (!q.empty()) {
            auto [u, flow] = q.front();
            q.pop();

            for (const int &v : G[u]) {
                if (par[v] == -1 && c[u][v]) {
                    par[v] = u;
                    int new_flow = std::min(flow, c[u][v]);
                    if (v == t) return new_flow;
                    q.emplace(v, new_flow);
                } 
            } 
        }

        return 0;
    }

    int MaxFlow(int s, int t) {
        int flow = 0;
        std::vector <int> par(V);
        for (int new_flow = 0; new_flow = bfs(s, t, par); flow += new_flow) {
            int curr = t;
            while (curr != s) {
                int prev = par[curr];
                c[prev][curr] -= new_flow;
                c[curr][prev] += new_flow;
                curr = prev;
            }
        }

        return flow;
    }
};

void Open() {
#ifndef ONLINE_JUDGE
    (void)!freopen("maxflow.in", "r", stdin);
    (void)!freopen("maxflow.out", "w", stdout);
#endif
}

int main() {
    Open();
    
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr); 

    int n, m; std::cin >> n >> m;
    EdmonsKarp ek(n);

    for (int i = 0; i < m; ++i) {
        int u, v, cap; std::cin >> u >> v >> cap;
        ek.addEdge(u - 1, v - 1, cap);
    }

    std::cout << ek.MaxFlow(0, n - 1) << '\n';
    return 0;
}