Cod sursa(job #3376672)

Utilizator SkibidiCezarCezar Bolba SkibidiCezar Data 18 noiembrie 2026 21:41:47
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
const int NMAX = 1000, MMAX = 5000;
int n, m, maxflux;
bool ok;
struct much{
    int a, b, c, f, per;
};
much a[2*MMAX+1];
vector <int> v[NMAX+1];
int last[NMAX+1];

void bfsclav(){
    queue <int> q;
    q.push(1);
    for(int i = 1; i <= n; i++){
        last[i] = -1;
    }
    last[1] = 0;
    int nod;
    while(!q.empty()){
        nod = q.front();
        q.pop();
        for(const int& nxt : v[nod]){
            if(a[nxt].f < a[nxt].c && last[a[nxt].b] == -1){
                last[a[nxt].b] = nxt;
                q.push(a[nxt].b);
            }
        }
    }
}

void fa_un_drum(){
    int nod = n, minim_ude = INT_MAX;
    while(nod != 1){
        minim_ude = min(minim_ude, a[last[nod]].c - a[last[nod]].f);
        nod = a[last[nod]].a;
    }
    maxflux += minim_ude;
    ok = 1;
    nod = n;
    while(nod != 1){
        a[last[nod]].f += minim_ude;
        a[a[last[nod]].per].f -= minim_ude;
        nod = a[last[nod]].a;
    }
}

void fa_drumurile(){
    for(const int& nxt : v[n]){
        if(last[a[nxt].b] != -1 && a[a[nxt].per].f < a[a[nxt].per].c){
            last[n] = a[nxt].per;
            fa_un_drum();
        }
    }
}

void flux(){
    ok = 1;
    while(ok){
        ok = 0;
        bfsclav();
        fa_drumurile();
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    fin >> n >> m;
    for(int i = 1; i <= m; i++){
        fin >> a[i].a >> a[i].b >> a[i].c;
        a[i].per = i + m;
        a[i+m] = {a[i].b, a[i].a, 0, 0, i};
        v[a[i].a].push_back(i);
        v[a[i].b].push_back(i + m);
    }
    flux();
    fout << maxflux;
    return 0;
}