Cod sursa(job #2954802)

Utilizator alex_bb8Banilean Alexandru-Ioan alex_bb8 Data 15 decembrie 2022 13:59:42
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

const int NMAX = 1002;

int n, m, RG[NMAX][NMAX];
vector<pair<int, int>> G[NMAX];

void read(){
    
    f >> n >> m;
    
    for(int i = 1; i <= m; ++i){
        int x, y, z;
        f >> x >> y >> z;
        G[x].push_back({y, z});
        RG[x][y] = z; 
    }
    
}

bool BFS(int s, int t, vector<int>& parent){
    fill(parent.begin(), parent.end(), -1);
    queue<int> Q;
    
    Q.push(s);
    parent[s] = -2;
    
    while(!Q.empty()){
        int node = Q.front();
        Q.pop();
        
        for(auto i : G[node]){
            if(parent[i.first] == -1 && RG[node][i.first] > 0){
                parent[i.first] = node;
                
                if(i.first == t)
                    return true;
                
                Q.push(i.first);
            }
        }
    }
    
    return false;
}

void solve(){
    
    int max_flow = 0, s = 1, t = n;
    vector<int> parent(NMAX, -1);
    
    while(BFS(s, t, parent)){
        
        int path_flow = INT_MAX;
        
        // find the max flow through the path
        for(int node = t; node != s; node = parent[node]){
            int aux = parent[node];
            path_flow = min(path_flow, RG[aux][node]);
        }
        
        // update
        for(int node = t; node != s; node = parent[node]){
            int aux = parent[node];
            RG[aux][node] -= path_flow;
            RG[node][aux] += path_flow;
        }
        
        max_flow += path_flow;
    }
    
    g << max_flow << '\n';
    
}

int main(){
    
    read();
    
    solve();

    return 0;
}