Cod sursa(job #3336419)

Utilizator petric_mariaPetric Maria petric_maria Data 24 ianuarie 2026 18:03:06
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");

int n, m, x, y, cost, dist[1005], flow[1005][1005], c[1005][1005];
int ans = 0;
vector<int> v[5005];

bool bfs (int source, int destination) {
    for (int i=1; i<=n; ++i)
        dist[i] = INT_MAX;
    dist[source] = 0;
    queue <int> q;
    q.push (source);

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

        for (auto x: v[k])
            if (c[k][x] > flow[k][x] && dist[x] > dist[k] + 1) {
                dist[x] = dist[k] + 1;
                q.push (x);
            }
    }
    return (dist[destination] != INT_MAX);
}

int maxFlow (int node, int destination, int max_flow) {
    if (max_flow == 0)
        return 0;
    if (node == destination)
        return max_flow;
    int total_flow = 0;

    for (auto x: v[node])
        if (dist[x] == dist[node] + 1) {
            int new_max_flow = min (max_flow, c[node][x] - flow[node][x]);

            int new_flow = maxFlow (x, destination, new_max_flow);
            flow[node][x] += new_flow;
            flow[x][node] -= new_flow;
            total_flow += new_flow;
        }
    return total_flow;
}


void Flow() {
    while (bfs (1, n))
        ans += maxFlow (1, n, INT_MAX);
}

int main()
{
    f >> n >> m;
    for (int i=1; i<=m; ++i) {
        f >> x >> y >> cost;
        v[x].push_back (y);
        v[y].push_back (x);
        c[x][y] = cost;
    }

    Flow();
    g << ans;
    return 0;
}