Cod sursa(job #3381022)

Utilizator edwarderzeAxante Edward-Ioan edwarderze Data 3 decembrie 2026 17:20:05
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>

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

int n, m;
int fluxMaxim = 0;
std::vector<std::vector<int>> flux, cost;
std::vector<std::vector<int>> adj_i, adj;

std::vector<int> bfs(int start, int target) {
    std::vector<int> viz(n + 1, 0);
    std::vector<int> tata(n + 1, 0);
    std::queue<int> q;
    q.push(start);
    viz[start] = 1;

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

        for (const auto& x : adj[nodeCurent]) {
            if (viz[x] == 0 && cost[nodeCurent][x] - flux[nodeCurent][x] > 0) {
                q.push(x);
                viz[x] = 1;
                tata[x] = nodeCurent;
                if (x == target) return tata;
            }
        }

        for (const auto& x : adj_i[nodeCurent]) {
            // Reverse edge: can only push flow back if there is existing flow on x -> nodeCurent
            if (viz[x] == 0 && flux[x][nodeCurent] > 0) {
                q.push(x);
                viz[x] = 1;
                tata[x] = -nodeCurent;
                if (x == target) return tata;
            }
        }
    }

    return {-1};
}

int main() {
    fin >> n >> m;
    flux.resize(n + 1, std::vector<int>(n + 1, 0));
    cost.resize(n + 1, std::vector<int>(n + 1, 0));
    adj_i.resize(n + 1);
    adj.resize(n + 1);

    for (int i = 0; i < m; ++i) {
        int x, y, z;
        fin >> x >> y >> z;

        adj_i[y].push_back(x);
        adj[x].push_back(y);

        flux[x][y] = 0;
        cost[x][y] += z;
    }

    std::vector<int> tata;
    while (true) {
        tata = bfs(1, n);
        if (tata.size() == 1) break;

        int x = n;
        int capMin = INT_MAX;
        while (x != 1) {
            if (tata[x] > 0)
                capMin = std::min(capMin, cost[tata[x]][x] - flux[tata[x]][x]);
            else if (tata[x] < 0)
                capMin = std::min(capMin, flux[x][-tata[x]]);
            x = std::abs(tata[x]);
        }

        // Update flow ONLY along the path from n back to 1
        x = n;
        while (x != 1) {
            if (tata[x] > 0)
                flux[tata[x]][x] += capMin;
            else if (tata[x] < 0)
                flux[x][-tata[x]] -= capMin;
            x = std::abs(tata[x]);
        }

        fluxMaxim += capMin;
    }

    fout << fluxMaxim;
    fin.close();
    fout.close();
    return 0;
}