Cod sursa(job #3122976)

Utilizator Theodor17Pirnog Theodor Ioan Theodor17 Data 21 aprilie 2023 14:30:41
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <queue>
#include <bitset>

using namespace std;

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

const int NMAX = 1e3;
const int inf = 2e9;

int flux[NMAX + 1][NMAX + 1], t[NMAX + 1];
vector <int> g[NMAX + 1];
bitset <NMAX + 1> viz;

bool bfs(int x, int n){

    viz = 0;
    viz[x] = 1;
    queue <int> q;
    q.push(x);

    while(!q.empty()){

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

        if(x == n)
            return true;

        for(auto y : g[x]){

            if(viz[y] == 1 || flux[x][y] <= 0)
                continue;

            t[y] = x;
            viz[y] = 1;
            q.push(y);

        }

    }

    return false;

}

int main(){

    int n = 0, m = 0;
    cin >> n >> m;

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

        int x = 0, y = 0, capacitate = 0;
        cin >> x >> y >> capacitate;

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


    }

    long long maxi = 0;

    while(bfs(1, n)){

        for(auto y : g[n]){

            if(viz[y] == 0 || flux[y][n] <= 0)
                continue;

            int mini = inf;
            t[n] = y;
            int x = n;

            while(x != 1){

                mini = min(mini, flux[t[x]][x]);
                x = t[x];

            }

            if(mini == 0)
                continue;

            maxi += mini;
            x = n;

            while(x != 1){

                flux[x][t[x]] += mini;
                flux[t[x]][x] -= mini;

                x = t[x];

            }

        }

    }

    cout << maxi;

    cin.close();
    cout.close();

    return 0;
}