Cod sursa(job #3321587)

Utilizator BuruianaRaresAndreiBuruiana Rares Andrei BuruianaRaresAndrei Data 10 noiembrie 2025 12:11:53
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("max_flow.in");
ofstream out("max_flow.out");

struct Edge {
    int from, to, cap, flux;
};

int n, m;
vector<Edge> edges;
vector<int> g[1005];

int bfs(int s, int t) {
    vector<int> parent_edge(n + 1, -1);
    vector<int> parent_node(n + 1, -1);
    queue<int> q;
    q.push(s);
    parent_node[s] = -2;
    while(!q.empty()) {
        int node = q.front(); q.pop();
        for(int edge : g[node]) {
            auto e = edges[edge];
            if(parent_node[e.to] == -1 && e.cap > e.flux) {
                parent_node[e.to] = node;
                parent_edge[e.to] = edge;
                if(e.to == t) goto found_path;
                q.push(e.to);
            }
        }
    }
    return 0;
    found_path:;
    int flux = INT_MAX;
    for(int node = t; node != s; node = parent_node[node]) {
        int edge = parent_edge[node];
        flux = min(flux, edges[edge].cap - edges[edge].flux);
    }
    for(int node = t; node != s; node = parent_node[node]) {
        int edge = parent_edge[node];
        edges[edge].flux += flux;
        edges[edge ^ 1].flux -= flux;
    }
    return flux;
}

int max_flow(int s, int t) {
    int flow = 0, new_flow = 0;
    while(new_flow = bfs(s, t)) {
        flow += new_flow;
    }
    return flow;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    in >> n >> m;
    for(int i = 1; i <= m; i++) {
        int from, to, cap; in >> from >> to >> cap;
        edges.push_back({from, to, cap, 0});
        g[from].push_back({edges.size() - 1});
        edges.push_back({to, from, 0, 0});
        g[to].push_back({edges.size() - 1});
    }
    out << max_flow(1, n) << '\n';

    return 0;
}