Cod sursa(job #3330302)

Utilizator pk360Sandulescu Ioan pk360 Data 18 decembrie 2025 17:15:31
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 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, 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] > 0) {
                tata[v] = u; viz[v] = true; cd.push(v);
                if (v == 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];
        c_min = min(c_min, cap[tc][c]);

        c = tc;
    }
    
    return c_min;
}

void rev_lant(int s, int t, int c_min) {
    while (t != s) {
        int tc = tata[t];
        
        cap[tc][t] -= c_min; // trimit flux, scade capacitatea reziduala
        cap[t][tc] += c_min; // primesc flux, creste capacitatea reziduala
        
        t = tc;
    } cout << endl;
}

int main() {
    int n, m; fin >> n >> m;
    graf.resize(n); tata.assign(n, -1);
    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[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;
}