Cod sursa(job #2984153)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 23 februarie 2023 17:32:10
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 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;

int capacitate[MAX][MAX] , flow[MAX][MAX] , n , m , x , y , c , t[MAX] , fl , gfl;

bool in[MAX];

vector <int> g[MAX];

bool bfs(){

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

        in[i] = t[i] = 0;
    }

    queue <pair<int,int>> q;

    t[1] = 0;

    q.push({1,inf});

    while(!q.empty()){

        x = q.front().first;
        fl = q.front().second;

        q.pop();

        in[x] = 1;

        for(auto it : g[x]){

            int auxfl = min(fl,capacitate[x][it]-flow[x][it]);

            if(!in[it] && auxfl>0){

                if( it == n ) return 1;

                t[it] = x;

                q.push({it,auxfl});

                in[it] = 1;
            }
        }
    }

    return 0;

}

int main()
{

    cin >> n >> m;

    while(m--){

        cin >> x >> y >> c;

        capacitate[x][y] = c;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    while(1){

        bool new_flow = bfs();

        if(!new_flow) break;

        for(auto it : g[n]){

            int aux = it , flmin = inf;

            while(t[aux]){

                flmin = min(flmin,capacitate[t[aux]][aux]-flow[t[aux]][aux]);

                aux = t[aux];
            }

            aux = it;

            flmin = min(flmin,capacitate[it][n]-flow[it][n]);

            gfl += flmin;

            flow[it][n] += flmin;
            flow[n][it] -= flmin;

            while(t[aux]){

                flow[t[aux]][aux] += flmin;
                flow[aux][t[aux]] -= flmin;

                aux = t[aux];
            }
        }

    }

    cout << gfl;

    return 0;
}