Cod sursa(job #2984597)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 24 februarie 2023 15:25:28
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;

const int inf = 1e9 + 1;

vector <int> g[MAX];

int capacitate[MAX][MAX] , n , m , x , y , c , flux[MAX][MAX];

struct Dinic{

    int level[MAX];

    bool viz[MAX];

    bool bfs( int source , int sink ){

        queue <int> q;

        int x;

        q.push(source);

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

            level[i] = 0;
        }

        level[source] = 1;

        while(!q.empty()){

            x = q.front();

            q.pop();

            for(auto it : g[x]){

                if(!level[it] && capacitate[x][it] - flux[x][it] > 0){

                    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;

        for(auto it : g[x]){

            if(capacitate[x][it] - flux[x][it] > 0 && level[it] == level[x]+1){

                int new_flow = dfs(it,sink,min(flow,capacitate[x][it]-flux[x][it]));

                if(new_flow){

                    flux[x][it] += new_flow;
                    flux[it][x] -= new_flow;
                    return new_flow;
                }
            }
        }

        return 0;
    }

    int dinicefectiv( int source , int sink){

        int max_flow = 0;

        while(bfs(source,sink)){

            while(1){

                int flow = dfs(source,sink,inf);

                if(!flow) break;

                max_flow += flow;
            }
        }

        return max_flow;
    }

}d;

int main(){

    cin >> n >> m;

    while(m--){

        cin >> x >> y >> c;

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

        capacitate[x][y] = c;
    }

    cout << d.dinicefectiv(1,n);

    return 0;
}