Cod sursa(job #3317846)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 25 octombrie 2025 17:20:32
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const string txt = "maxflow";
const int inf = 1e9;

ifstream f(txt + ".in");
ofstream g(txt + ".out");

int n, m, cap[1005][1005], flow[1005][1005], dist[1005], ans, fr[1005];
vector<int> v[1005];

static bool bfs()
{
    for (int i = 1; i <= n; i++) fr[i] = 0, dist[i] = inf;
    queue<int> q; while (!q.empty()) q.pop();

    q.push(1); dist[1] = 1;
    while (!q.empty())
    {
        int nod = q.front(); fr[nod] = 1;
        for(auto x : v[nod])
            if (dist[x] > dist[nod] + 1 && flow[nod][x] < cap[nod][x]) {
                dist[x] = dist[nod] + 1;
                q.push(x);
            }

        q.pop();
    }

    return fr[n];
}

static int maxflow(int nod, int d, int maxi)
{
    if (maxi == 0) return 0;
    if (nod == d) return maxi;

    int tot = 0;
    for (auto x : v[nod])
    {
        if (dist[x] != dist[nod] + 1) continue;
        int nr = maxflow(x, d, min(maxi - tot, cap[nod][x] - flow[nod][x]));
        flow[nod][x] += nr; flow[x][nod] -= nr; tot += nr;
    }

    return tot;
}

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

    while (bfs()) 
        ans += maxflow(1, n, inf);

    g << ans;
    return 0;
}