Cod sursa(job #3333602)

Utilizator RaduCalisovCalisovRadu RaduCalisov Data 14 ianuarie 2026 14:10:53
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
using namespace std;

int n,m;
vector<vector<int>> v;
vector<vector<int>> flux;
vector<vector<int>> cap;

int bfs(){
    vector<bool> checked(n+1,0);
    vector<int> p(n+1);
    queue<int> q;
    p[1] = 0;
    checked[1] = 1;
    q.push(1);

    while(q.size()){
        int nod = q.front();
        q.pop();

        for(int i = 0 ; i < v[nod].size();i++){
            int newnod = v[nod][i];
            if(checked[newnod] == 0 and cap[nod][newnod] - flux[nod][newnod] > 0){
                checked[newnod] = 1;
                q.push(newnod);
                p[newnod] = nod;
            }
        }
    }

    if(checked[n] == 0)
        return 0;

    int y = n;
    int minim = 1e9;

    while(p[y]!=0){
        int x = p[y];
        minim = min(minim,cap[x][y] - flux[x][y]);

        y = x;
    }

    y = n;

    while(p[y]!=0){
        int x = p[y];
        flux[x][y] += minim;
        flux[y][x] -= minim;

        y = x;
    }
    return minim;
}

int main() {
    ifstream cin("fluxmaxim.in");
    ofstream cout("fluxmaxim.out");

    cin>>n>>m;
    v.resize(n+1);
    flux.resize(n+1,vector<int>(n+1,0));
    cap.resize(n+1,vector<int>(n+1,0));

    for(int i=1;i<=m;i++){
        int x,y,z;
        cin>>x>>y>>z;
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y] = z;
    }
    int sumFlow = 0;
    int flow;

    while((flow = bfs()) != 0)
        sumFlow += flow;
    
    cout<<sumFlow;
}