Cod sursa(job #3357920)

Utilizator theodor17__Theodor Ioan Pirnog theodor17__ Data 13 iunie 2026 21:48:53
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

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

const int NMAX = 1e3;

vector <int> g[NMAX + 1];
int cap[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1], acc[NMAX + 1];
int p[NMAX + 1];

int bfs(int s, int t) {

    memset(p, -1, 4 * (NMAX + 1));

    queue <int> q;
    q.push(s);
    p[s] = s;
    acc[s] = (int) 1e9;

    while (!q.empty()) {

        int u = q.front();
        q.pop();

        for (auto v : g[u]) {
            if (p[v] == -1 && cap[u][v] - flux[u][v] > 0) { // vecinul nu a fost vizitat si mai pot imbunatati fluxul
                p[v] = u;

                acc[v] = min(acc[u], cap[u][v] - flux[u][v]);
                if (v == t) {
                    return acc[v];
                }

                q.push(v);

            }
        }

    }

    return 0;
}

int max_flow (int s, int t) {

    int maxFlow = 0;
    while (1) {

        int flow = bfs(s, t);
        if (flow == 0) {
            break;
        }

        maxFlow += flow;
        int v = t;
        while (v != s) {

            int u = p[v];
            flux[u][v] += flow;
            flux[v][u] -= flow;

            v = u;
        }

    }

    return maxFlow;
}

int main() {

    int n = 0, m = 0;
    fin >> n >> m;

    int u = 0, v = 0, c = 0;
    for (int i = 0; i < m; i++) {
        fin >> u >> v >> c;
        cap[u][v] += c;

        g[u].push_back(v);
        g[v].push_back(u); // ADAUGAM arc invers drept arc rezidual
    }

    int flow = max_flow(1, n);
    fout << flow;

    return 0;
}