Cod sursa(job #2986835)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 1 martie 2023 12:53:33
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream cin("maxflow.in");
ofstream cout("maxflow.out");

const int MAX = 1e3 + 1;

const int inf = 1e9 + 1;

int c[MAX][MAX] , f[MAX][MAX] , n , m , x , y , cap , level[MAX] , ef[MAX];

vector <int> g[MAX];

bool bfs(){

    queue <int> q;

    for(int i = 1 ; i <= n ; i++){

        level[i] = ef[i] = 0;
    }

    q.push(1);

    level[1] = 1;

    while(!q.empty()){

        int x = q.front();

        q.pop();

        for(auto it : g[x]){

            if(!level[it] && (c[x][it]-f[x][it])>0){

                level[it] = level[x]+1;

                if(it == n) return 1;

                q.push(it);
            }
        }
    }

    return 0;

}

int dfs( int x , int flow ){

    int sz = g[x].size();

    for(int i = ef[x] ; i < sz ; i++){

        int it = g[x][i];

        if(level[it] == level[x] + 1){

            flow = dfs(it,min(flow,c[x][it]-f[x][it]));

            if(flow){

                f[x][it] += flow;
                f[it][x] -= flow;

                return flow;
            }
        }

        ef[x]++;
    }

    return flow;

}

int main(){

    cin >> n >> m;

    while(m--){

        cin >> x >> y >> cap;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = cap;
    }

    int flow = 0;

    while(bfs()){

        while(1){

            int x = dfs(1,inf);

            if(!x) break;

            flow+=x;
        };
    }

    cout << flow;

    return 0;
}