Cod sursa(job #3270988)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 24 ianuarie 2025 23:13:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <climits>

using namespace std;

struct Edge {
    int to, rev, capacity;
};

class Dinic {
    int n;
    vector<vector<Edge>> adj;
    vector<int> level, ptr;

public:
    Dinic(int n) : n(n), adj(n + 1) {}

    void add_edge(int from, int to, int capacity) {
        adj[from].push_back({to, (int)adj[to].size(), capacity});
        adj[to].push_back({from, (int)adj[from].size() - 1, 0});
    }

    bool bfs(int s, int t) {
        level.assign(n + 1, -1);
        queue<int> q;
        q.push(s);
        level[s] = 0;

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

            for (const Edge& e : adj[u]) {
                if (e.capacity > 0 && level[e.to] == -1) {
                    level[e.to] = level[u] + 1;
                    q.push(e.to);
                    if (e.to == t) return true;
                }
            }
        }
        return false;
    }

    int dfs(int u, int t, int flow) {
        if (u == t) return flow;

        for (int& i = ptr[u]; i < adj[u].size(); i++) {
            Edge& e = adj[u][i];
            if (e.capacity > 0 && level[e.to] == level[u] + 1) {
                int min_flow = min(flow, e.capacity);
                int pushed = dfs(e.to, t, min_flow);
                if (pushed > 0) {
                    e.capacity -= pushed;
                    adj[e.to][e.rev].capacity += pushed;
                    return pushed;
                }
            }
        }
        return 0;
    }

    int max_flow(int s, int t) {
        int total_flow = 0;
        while (bfs(s, t)) {
            ptr.assign(n + 1, 0);
            while (int pushed = dfs(s, t, INT_MAX)) {
                total_flow += pushed;
            }
        }
        return total_flow;
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

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

    int n, m;
    cin >> n >> m;

    Dinic dinic(n);

    for (int i = 0; i < m; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        dinic.add_edge(x, y, z);
    }

    cout << dinic.max_flow(1, n) << endl;

    return 0;
}