Cod sursa(job #3129305)

Utilizator razviii237Uzum Razvan razviii237 Data 13 mai 2023 21:44:05
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
// CHAT GPT
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

const int INF = numeric_limits<int>::max();

struct Edge {
    int from, to, capacity, flow;
};

void push(Edge& e, vector<int>& excess) {
    int flow = min(excess[e.from], e.capacity - e.flow);
    excess[e.to] += flow;
    excess[e.from] -= flow;
    e.flow += flow;
}

void relabel(int u, vector<int>& height, vector<vector<Edge>>& graph) {
    int min_height = INF;
    for (const auto& e : graph[u]) {
        if (e.capacity > e.flow) {
            min_height = min(min_height, height[e.to]);
        }
    }
    if (min_height < INF) {
        height[u] = min_height + 1;
    }
}

void discharge(int u, vector<int>& excess, vector<int>& height, vector<vector<Edge>>& graph) {
    while (excess[u] > 0) {
        for (auto& e : graph[u]) {
            if (e.capacity > e.flow && height[u] == height[e.to] + 1) {
                push(e, excess);
                if (excess[u] == 0) {
                    return;
                }
            }
        }
        relabel(u, height, graph);
    }
}

int max_flow(vector<vector<Edge>>& graph, int source, int sink) {
    int V = graph.size();
    vector<int> excess(V, 0), height(V, 0);
    height[source] = V;
    excess[source] = INF;

    for (auto& e : graph[source]) {
        push(e, excess);
    }

    while (true) {
        bool done = true;
        for (int u = 0; u < V; u++) {
            if (u != source && u != sink && excess[u] > 0) {
                int old_height = height[u];
                discharge(u, excess, height, graph);
                if (height[u] > old_height) {
                    done = false;
                }
            }
        }
        if (done) {
            break;
        }
    }

    int max_flow = 0;
    for (const auto& e : graph[source]) {
        max_flow += e.flow;
    }
    return max_flow;
}

int main() {
    int n, m, x, y, z, start, end;
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    cin >> n >> m;
    vector <vector<Edge> > v(n);
    for(int i = 1; i <= m; i ++) {
        cin >> x >> y >> z;
        x--;
        y--;

        v[x].push_back({x, y, z, 0});
        v[y].push_back({y, x, 0, 0});
    }

    cout << max_flow(v, 0, n-1) << '\n';
    return 0;
}