Cod sursa(job #3039393)

Utilizator DordeDorde Matei Dorde Data 28 martie 2023 15:09:37
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int const inf = 1e9;
int n , m , a , b;
int t[1001] , fl[1001] , viz[1001];
int f[1001][1001];
bool bfs(){
    fill(viz + 1 , viz + 1 + n , 0);
    queue<int> q;
    q.push(1);
    viz[1] = 1 , fl[1] = inf;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        for(int y = 1 ; y < n ; ++ y){
            if(f[x][y] > 0 && !viz[y]){
                viz[y] = 1;
                t[y] = x;
                fl[y] = min(fl[x] , f[x][y]);
                q.push(y);
            }
        }
    }
    for(int i = 1 ; i < n ; ++ i)
        if(f[i][n] > 0 && viz[i])
            return true;
    return false;
}
int upd(int x){
    int y = x , flow = inf;
    while(t[x]){
        flow = min(flow , t[x]);
        x = t[x];
    }
    x = y;
    while(t[x]){
        f[t[x]][x] -= flow;
        f[x][t[x]] += flow;
        x = t[x];
    }
    return flow;
}
int maxflow(){
    int flow(0);
    while(bfs()){
        for(int i = 1 ; i < n ; ++ i){
            if(viz[i] && f[i][n] > 0){
                t[n] = i;
                flow += upd(n);
            }
        }
    }
    return flow;
}
int main()
{
    fin >> n >> m;
    for(int i = 1 ; i <= m ; ++ i){
        fin >> a >> b >> f[a][b];
    }
    fout << maxflow() << '\n';
    return 0;
}