Cod sursa(job #3337240)

Utilizator iulia_learning_timeLearning Time iulia_learning_time Data 27 ianuarie 2026 06:38:52
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm> 

using namespace std;

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

const int INF = 1e9;

int N, M;
vector<vector<int>> adj;
vector<vector<int>> capacity;


bool bfs(int s, int t, vector<int>& parent){
    fill (parent.begin(), parent.end(), -1);
    queue<int> Q;
    Q.push(s);
    parent[s] = -2; // Marcăm sursa vizitată (valoare diferită de -1)

    while(Q.size() > 0){
        int u = Q.front();
        Q.pop();

        if(u == t)
            return true;

        for (auto vecin : adj[u]){
            if (parent[vecin] == -1 && capacity[u][vecin] > 0 ){
                parent[vecin] = u;
                Q.push(vecin);
            }
        }
    }
    return false;
}


int main(){
    fin >> N >> M;
    adj.resize(N+1);
    capacity.assign(N+1, vector<int>(N+1,0));

    for (int i = 0 ; i < M ; i++){
        int u, v, c;
        fin >> u >> v >> c;
        adj[u].push_back(v);
        adj[v].push_back(u);
        capacity[u][v] = c;
    }

    int max_flow = 0;
    vector<int> parent(N+1);

    while(bfs(1, N, parent)){
        int path_flow = INF;

        for(int v = N ; v != 1 ; v = parent[v]){
            int u = parent[v];
            path_flow =  min(path_flow, capacity[u][v]);
        }

        for (int v = N ; v!= 1 ; v = parent[v]){
            int u = parent[v];
            capacity[u][v] -= path_flow;
            capacity[v][u] += path_flow;
        }

        max_flow +=path_flow;
    }

    fout << max_flow;
}