Cod sursa(job #3330300)

Utilizator pk360Sandulescu Ioan pk360 Data 18 decembrie 2025 16:58:03
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

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

#define inf 1e9

vector<vector<int>> graf, graf_r, flux, cap;
vector<int> tata;
vector<bool> viz;

bool bfs(int n, int s, int t) {
    viz.assign(n, false);
    queue<int> cd; cd.push(s); viz[s] = true;
    
    while (!cd.empty()) {
        int u = cd.front(); cd.pop();
        
        for (int v : graf[u]) {
            if (!viz[v] && cap[u][v] - flux[u][v] > 0) {
                tata[v] = u; viz[v] = true; cd.push(v);
                if (v == t) { return true; }
            }
        }
        
        for (int vr : graf_r[u]) {
            if (!viz[vr] && flux[vr][u] > 0) {
                tata[vr] = -u; viz[vr] = true; cd.push(vr);
                if (vr == t) { return true; }
            }
        }
    }
    
    return false;
}

int min_capacity(int s, int t) {
    int c = t, c_min = inf;
    
    while (c != s) {
        int tc = tata[c];
        if (tc >= 0) { c_min = min(c_min, cap[tc][c] - flux[tc][c]); }
        else { c_min = min(c_min, flux[c][abs(tc)]); }
        
        c = abs(tc);
    }
    
    return c_min;
}

void rev_lant(int s, int t, int c_min) {
    while (t != s) {
        int tc = tata[t];
        if (tc >= 0) { flux[tc][t] += c_min; }
        else { flux[t][abs(tc)] -= c_min; }
        
        t = abs(tc);
    } cout << endl;
}

int main() {
    int n, m; fin >> n >> m;
    graf.resize(n); graf_r.resize(n); tata.assign(n, -1);
    flux.assign(n, vector<int>(n, 0)); cap.assign(n, vector<int>(n, 0));
    
    for (int i = 0; i < m; i++) {
        int x, y, c; fin >> x >> y >> c; x--; y--;
        graf[x].push_back(y);
        graf_r[y].push_back(x);
        cap[x][y] = c;
    }
    
    // while bfs din s-t gaseste drum
    // determinam cap minima (pe vectorul de tati)
    // pe acelasi drum modificam fluxul cu capacitatea minima
    int s = 0, t = n - 1, fl = 0; 
    while (bfs(n, s, t)) {
        int cap_min = min_capacity(s, t);
        rev_lant(s, t, cap_min);
        
        fl += cap_min;
    }
    
    fout << fl;

    return 0;
}