Cod sursa(job #2984174)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 23 februarie 2023 18:00:57
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 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] = 0;
        t[i] = 0;
    }

    queue <int> q;

    q.push(1);

    in[1] = 1;

    while(!q.empty()){

        x = q.front();

        q.pop();

        for(auto it : g[x]){

            if(!in[it] && (capacitate[x][it]-flow[x][it])){

                if( it == n ) return 1;

                in[it] = 1;

                t[it] = x;

                q.push(it);
            }
        }
    }

    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 = capacitate[it][n]-flow[it][n];

            if (t[it] == 0 || capacitate[it][n] - flow[it][n]<= 0)  continue;

            while(t[aux]){

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

                aux = t[aux];
            }

            aux = it;

            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;
}