Cod sursa(job #3357909)

Utilizator theodor17__Theodor Ioan Pirnog theodor17__ Data 13 iunie 2026 21:16:47
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <bitset>

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];

bool dfs(int node, vector <int> &path, bitset <NMAX + 1> &viz, int n) {

    viz[node] = 1;
    path.push_back(node);

    if (node == n) {
        return true;
    }

    for (auto y : g[node]) {
        if (viz[y] == 0 && cap[node][y] - flux[node][y] > 0) {
            if (dfs(y, path, viz, n)) {
                return true;
            }
        }
    }

    path.pop_back();
    return false;
}

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
    }

    vector <int> path;
    bitset <NMAX + 1> viz;

    int flux_maxim = 0;
    while (true) {

        path.clear();
        viz.reset();

        if (!dfs(1, path, viz, n)) {
            break;
        }

        int f = 1e9;
        for (int i = 0; i < path.size() - 1; i++) {
            f = min(f, cap[path[i]][path[i + 1]] - flux[path[i]][path[i + 1]]);
        }

        for (int i = 0; i < path.size() - 1; i++) {
            flux[path[i]][path[i + 1]] += f;
            flux[path[i + 1]][path[i]] -= f;
        }

        flux_maxim += f;
    }

    fout << flux_maxim;
    return 0;
}