Cod sursa(job #3324998)

Utilizator vlad2009Vlad Tutunaru vlad2009 Data 24 noiembrie 2025 14:21:01
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/extc++.h>

using namespace std;

typedef long long ll;

const int INF = 1e9;

struct Flow {
    struct Edge {
        int u, v, cap;
    };
    
    int n;
    vector<vector<int>> g;
    vector<int> dist;
    vector<Edge> e;
    
    Flow(int nn) {
        n = nn;
        g.resize(n + 1);
        dist.resize(n + 1);
    }
    
    void add_edge(int u, int v, int cap) {
        g[u].push_back(e.size());
        e.push_back({u, v, cap});
        g[v].push_back(e.size());
        e.push_back({v, u, 0});
    }
    
    bool bfs(int a, int b) {
        for (int i = 0; i < dist.size(); ++i) dist[i] = -1;
        queue<int> q;
        q.push(a);
        dist[a] = 0;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (auto id : g[u]) {
                auto [uu, v, cap] = e[id]; 
                if (cap != 0 && dist[v] == -1) {
                    dist[v] = dist[u] + 1;
                    q.push(v);
                }
            }
        }
        return dist[b] != -1;
    }
    
    int dfs(int u, int T, int F) {
        if (F == 0 || u == T) return F;
        int ret = 0;
        for (auto id : g[u]) {
            auto [uu, v, cap] = e[id];
            if (dist[u] + 1 == dist[v]) {
                int push = dfs(v, T, min(F, cap));
                F -= push;
                ret += push;
                e[id].cap -= push;
                e[id ^ 1].cap += push;
            }
        }
        return ret;
    }
    
    int max_flow(int s, int t) {
        int ans = 0;
        while (bfs(s, t)) ans += dfs(s, t, INF);
        return ans;
    }
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    Flow f(n);
    for (int i = 0; i < m; ++i) {
        int a, b, c;
        cin >> a >> b >> c;
        f.add_edge(a, b, c);
    }
    cout << f.max_flow(1, n) << "\n";
    return 0;
}