Cod sursa(job #3122975)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 21 aprilie 2023 14:26:02
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int MAX = 1e3 + 1;

vector <int> g[MAX];

int f[MAX][MAX] , cap[MAX][MAX] , n , m;

struct Dinic{

    int level[MAX] , ef[MAX];

    bool bfs( int source , int sink ){

        queue <int> q;

        q.push(source);

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

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

        level[source] = 1;

        int x;

        while(!q.empty()){

            x = q.front();
            q.pop();

            for(auto it : g[x]){

                if(!level[it] && (cap[x][it] - f[x][it])){

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

                    if(it == sink) return 1;

                    q.push(it);
                }
            }
        }

        return 0;
    }

    int dfs( int x , int sink , int flow){

        if( x == sink ){

            return flow;
        }

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

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

            int it = g[x][ef[x]];

            if(level[x] == (level[it]-1) && (cap[x][it]-f[x][it]>0)){

                int new_flow = min(flow,cap[x][it]-f[x][it]);

                new_flow = dfs(it,sink,new_flow);

                if(new_flow){

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

                    return new_flow;
                }
            }
        }

        return 0;
    }
}d;

int main(){

    cin >> n >> m;

    int x , y , aux;

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

        cin >> x >> y >> aux;

        g[x].push_back(y);
        g[y].push_back(x);

        cap[x][y] = aux;
    }

    int flow_delicios = 0;

    while(d.bfs(1,n)){

        int new_flow;

        while(1){

            new_flow = d.dfs(1,n,1e9);

            if(!new_flow) break;

            flow_delicios += new_flow;
        }
    }

    cout << flow_delicios;

    return 0;
}