Cod sursa(job #3288471)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 22 martie 2025 15:03:49
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;
#define pb push_back
const int N = 10005, INF = 1e9;

int n, m, capacity[1005][1005];
vector<int> parent;
vector<pair<int, int> > g[N];

int bfs(int s, int t) {
    fill(parent.begin(), parent.end(), -1);
    parent[s] = 0;
    queue<pair<int, int>> Q;
    Q.push({s, INF});
    while (!Q.empty()) {
        int cur_node = Q.front().first;
        int cur_flow = Q.front().second;
        Q.pop();
        for (auto &it: g[cur_node]) {
            int nxt_node = it.first, edge_flow = it.second;
            if (parent[nxt_node] == -1 && capacity[cur_node][nxt_node]) {
                parent[nxt_node] = cur_node;
                int new_flow = min(cur_flow, capacity[cur_node][nxt_node]);
                if (nxt_node == t)
                    return new_flow;
                Q.push({nxt_node, new_flow});
            }
        }
    }
    return 0;
}

int max_flow(int s, int t) {
    int flow = 0;
    int new_flow = bfs(s, t);
    while (new_flow) {
        flow += new_flow;
        /// scad capacitatea
        int cur = t;
        while (cur != s) {
            int prev = parent[cur];
            capacity[cur][prev] += new_flow;
            capacity[prev][cur] -= new_flow;
            cur = prev;
        }
        new_flow = bfs(s, t);
    }
    return flow;
}

int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    cin >> n >> m;
    parent.resize(n + 5);
    parent.assign(n + 5, 0);
    for (int i = 1; i <= m; i++) {
        int u, v, cst;
        cin >> u >> v >> cst;
        capacity[u][v] = cst;
        capacity[v][u] = 0;
        g[u].pb({v, cst});
        g[v].pb({u, 0});
    }
    cout << max_flow(1, n);
    return 0;
}