Cod sursa(job #3267939)

Utilizator RolandPetreanPetrean Roland RolandPetrean Data 13 ianuarie 2025 08:21:03
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
// pregatire pentru iiot
#include <bits/stdc++.h>
using namespace std;

using pi = array<int, 2>;

const int INF = 1e9;

struct Dinic {
    struct Edge {
        int from, to, cap, next_edge;
    };
    int n;
    vector<Edge> edges;
    vector<int> first_edge;

    Dinic(int n) : n(n), first_edge(n, -1) {}

    void add_edge(int from, int to, int cap) {
        edges.push_back({from, to, cap, first_edge[from]});
        first_edge[from] = edges.size() - 1;
        edges.push_back({to, from, 0, first_edge[to]});
        first_edge[to] = edges.size() - 1;
    }

    vector<int> dist;
    void bfs(int s) {
        dist.assign(n, INF);
        queue<int> q;
        q.push(s);
        dist[s] = 0;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (int i = first_edge[u]; i != -1; i = edges[i].next_edge) {
                int v = edges[i].to;
                if (edges[i].cap > 0 && dist[v] == INF) {
                    dist[v] = dist[u] + 1;
                    q.push(v);
                }
            }
        }
    }

    int push_flow(int u, int t, int maxf) {
        if (u == t) {
            return maxf;
        }
        int f = 0;
        for (int i = first_edge[u]; i != -1; i = edges[i].next_edge) {
            int v = edges[i].to;
            if (dist[v] == dist[u] + 1) {
                int here = push_flow(v, t, min(maxf, edges[i].cap));
                f += here;
                maxf -= here;
                edges[i].cap -= here;
                edges[i ^ 1].cap += here;
            }
        }
        return f;
    }

    int maxflow(int s, int t) {
        int f = 0;
        do {
            bfs(s);
            f += push_flow(s, t, INF);
        } while (dist[t] != INF);
        return f;
    }
};

int main() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");

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

    Dinic flux(n + 1);
    for (int i = 0; i < m; ++i) {
        int u, v, c;
        cin >> u >> v >> c;
        flux.add_edge(u, v, c);
    }

    cout << flux.maxflow(1, n);
}