Cod sursa(job #3194063)

Utilizator mex7Alexandru Valentin mex7 Data 16 ianuarie 2024 20:08:28
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>
#define cin fin
#define cout fout
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n, m;
vector <int> in[1005], out[1005];
int limit[1005][1005], cost[1005][1005];
pair <int, int> prevNode[1005];

void update(int currNode, int add) {
    if (currNode == 1) {
        return;
    }

    update(prevNode[currNode].first, add);

    cost[prevNode[currNode].first][currNode] += add * prevNode[currNode].second;

}

int main() {
    cin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int u, v, cost;
        cin >> u >> v >> cost;
        out[u].push_back(v);
        in[v].push_back(u);
        limit[u][v] = cost;
    }

    const int start = 1;
    const int endNode = n;
    bool saturated = false;
    while (!saturated) {
        saturated = true;

        queue <pair <int, int> > q;
        bitset <1005> reached;
        int change = 0;
        q.push({start, INT_MAX});
        while (!q.empty()) {
            int front = q.front().first;
            int currMin = q.front().second;
            q.pop();
            if (front == endNode) {
                saturated = false;
                change = currMin;
                break;
            }

            for (int next : out[front]) {
                int residual = limit[front][next] - cost[front][next];
                if (!reached[next] && residual) {
                    reached[next] = 1;
                    q.push({next, min(currMin, residual)});
                    prevNode[next] = {front, 1};
                }
            }

            for (int next : in[front]) {
                int residual = cost[next][front];
                if (!reached[next] && residual) {
                    reached[next] = 1;
                    q.push({next, min(currMin, residual)});
                    prevNode[next] = {front, -1};
                }
            }
        }

        if (!saturated) {
            update(endNode, change);
        }
    }

    // for (int i = 1; i <= n; ++i) {
    //     for (int j = 1; j <= n; ++j) {
    //         cout << cost[i][j] << "/" << limit[i][j] << ' ';
    //     }
    //     cout << '\n';
    // }
    int maxFlux = 0;
    for (int next : out[start]) {
        maxFlux += cost[start][next];
    }

    cout << maxFlux;

    return 0;
}