Cod sursa(job #3332197)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 4 ianuarie 2026 22:51:37
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 1005;

vector <int> g[nmax];

int n, m;
int rez;

int cap[nmax][nmax], flow[nmax][nmax];
int distv[nmax], ptr[nmax];

bool bfs (int s, int dest)
{
    for (int i = 1; i <= n; i++)
        distv[i] = INT_MAX, ptr[i] = 0;

    queue <int> q;
    distv[s] = 0;
    q.push (s);

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

        for (auto x : g[node])
        {
            if (distv[x] == INT_MAX && cap[node][x] > flow[node][x])
            {
                distv[x] = distv[node] + 1;
                q.push (x);
            }
        }
    }

    return distv[dest] != INT_MAX;
}

int max_flow (int node, int dest, int pushed)
{
    if (pushed == 0) return 0;
    if (node == dest) return pushed;

    for (int& i = ptr[node]; i < (int)g[node].size (); i++)
    {
        int x = g[node][i];

        if (distv[x] != distv[node] + 1) continue;

        int rem = cap[node][x] - flow[node][x];
        if (rem <= 0) continue;

        int tr = max_flow (x, dest, min (pushed, rem));
        if (tr == 0) continue;

        flow[node][x] += tr;
        flow[x][node] -= tr;

        return tr;
    }

    return 0;
}

void compute_flow (int s, int dest)
{
    while (bfs (s, dest))
    {
        while (true)
        {
            int pushed = max_flow (s, dest, INT_MAX);
            if (pushed == 0) break;
            rez += pushed;
        }
    }
}

int main ()
{
    fin >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;

        if (cap[x][y] == 0 && cap[y][x] == 0)
        {
            g[x].push_back (y);
            g[y].push_back (x);
        }
        cap[x][y] += c;
    }

    compute_flow (1, n);

    fout << rez;
    return 0;
}