Cod sursa(job #3378485)

Utilizator TonyyAntonie Danoiu Tonyy Data 26 noiembrie 2026 16:54:23
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int nMax = 1001;
int n, m;
vector<int> g[nMax], t[nMax];
vector<vector<int>> cost(nMax, vector<int>(nMax));
vector<vector<int>> flux(nMax, vector<int>(nMax));
vector<int> parent(nMax);
queue<int> q;
bitset<nMax> visited;

bool bfs(int src, int target) {
    fill(parent.begin(), parent.end(), 0);
    visited.reset();
    q.push(src);
    visited[src] = 1;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (const auto& neighbour : g[node]) {
            if (!visited[neighbour] && cost[node][neighbour] - flux[node][neighbour] > 0) {
                q.push(neighbour);
                visited[neighbour] = 1;
                parent[neighbour] = node;
                if (neighbour == target) {
                    return true;
                }
            }
        }
        for (const auto& neighbour : t[node]) {
            if (!visited[neighbour] && flux[neighbour][node] > 0) {
                q.push(neighbour);
                visited[neighbour] = 1;
                parent[neighbour] = -node;
                if (neighbour == target) {
                    return true;
                }
            }
        }
    }
    return false;
}

int fordfulkerson(int src, int target) {
    int maxFlux = 0;
    while (bfs(src, target)) {
        int minCap = 1e9;
        for (int node = target; parent[node]; node = abs(parent[node])) {
            if (parent[node] > 0) {  // parent -> node
                minCap = min(minCap, cost[parent[node]][node] - flux[parent[node]][node]);
            } else {  // node -> parent
                minCap = min(minCap, flux[node][parent[node]]);
            }
        }
        for (int node = target; parent[node]; node = abs(parent[node])) {
            if (parent[node] > 0) {  // parent -> node
                flux[parent[node]][node] += minCap;
            } else {  // node -> parent
                flux[node][parent[node]] -= minCap;
            }
        }
        maxFlux += minCap;
    }
    return maxFlux;
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v, w;
        fin >> u >> v >> w;
        g[u].push_back(v);
        t[v].push_back(u);
        cost[u][v] = w;
    }
    fout << fordfulkerson(1, n) << "\n";

    return 0;
}