Cod sursa(job #3158919)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 20 octombrie 2023 02:40:48
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <bits/stdc++.h>

#define NMAX 1001
#define INF 1e9

using namespace std;

int n, m, x, y, c;
vector<int> neighbours[NMAX];
queue<int> excess_vertices;
int flow[NMAX][NMAX], capacity[NMAX][NMAX], excess[NMAX], current_arc[NMAX], label[NMAX];

void push(int u, int v) {
    int pushed_flow = min(excess[u], capacity[u][v] - flow[u][v]);

    if (pushed_flow == 0) {
        return;
    }

    flow[u][v] += pushed_flow;
    flow[v][u] -= pushed_flow;
    excess[u] -= pushed_flow;
    excess[v] += pushed_flow;

    if (excess[v] == pushed_flow) {
        excess_vertices.push(v);
    }
}

void relabel(int node) {
    int new_label = INF;

    for (auto neighbour : neighbours[node]) {
        if (capacity[node][neighbour] - flow[node][neighbour] > 0) {
            new_label = min(new_label, label[neighbour] + 1);
        }
    }

    label[node] = new_label;
}

void discharge(int node) {
    while (excess[node]) {
        if (current_arc[node] == (int)neighbours[node].size()) {
            current_arc[node] = 0;
            relabel(node);
        } else {
            int neighbour = neighbours[node][current_arc[node]];
            if (capacity[node][neighbour] - flow[node][neighbour] && label[node] == label[neighbour] + 1) {
                push(node, neighbour);
            } else {
                current_arc[node]++;
            }
        }
    }
}

int max_flow(int source, int sink) {
    excess[source] = INF;
    label[source] = n;

    for (int i = 1; i <= n; i++) {
        if (i == source) {
            continue;
        }

        if (capacity[source][i] > 0) {
            push(source, i);
        }
    }

    while (!excess_vertices.empty()) {
        int node = excess_vertices.front();
        excess_vertices.pop();

        if (node == source || node == sink)
            continue;

        discharge(node);
    }

    int max_flow = 0;
    for (int i = 1; i <= n; i++) {
        max_flow += flow[i][sink];
    }

    return max_flow;
}

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

    scanf("%d%d", &n, &m);

    for (int i = 1; i <= m; i++) {
        scanf("%d%d%d", &x, &y, &c);
        neighbours[x].push_back(y);
        neighbours[y].push_back(x);
        capacity[x][y] = c;
    }

    printf("%d\n", max_flow(1, n));

    return 0;
}