Cod sursa(job #3184710)

Utilizator PopaBiancaPopa Bianca Daniela PopaBianca Data 16 decembrie 2023 16:23:13
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int const nMax = 1000 + 5;
int const flowMax = 110000 + 5;

int n, m, x, y, cap;

struct nod{
    int fMax, fSent;

}a;

vector <vector<nod>> graph(nMax, vector<nod>(nMax,{0,0}));

int findCostPath(vector<int>& f){
    int x = n;
    int ans = flowMax;
    while (x != 1)
    {
        int dad = abs(f[x]);
        bool invers = f[x] < 0;
        
        if(invers)
            ans = min(ans, graph[dad][x].fSent);
        else
            ans = min(ans, graph[dad][x].fMax - graph[dad][x].fSent);
        
        x = dad;
    }

    x = n;
    while (x != 1)
    {
        int dad = abs(f[x]);
        bool invers = f[x] < 0;
        if(invers)
            graph[x][dad].fSent -= ans;
        else
            graph[dad][x].fSent += ans;
        x = dad;
    }
    return ans;
}


int findPath(){
    vector <int> f(n+2, 0);
    vector <bool> viz(n+2, false);
    queue <int> q;

    int ans = 0;
    bool ok = false;

    q.push(1);
    viz[1] = true;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        //cout << x << " ";

        for(int i = 1; i <=n; i++){
            if(!viz[i]){
                if(graph[x][i].fMax - graph[x][i].fSent > 0){
                    f[i] = x;

                    if(i == n){
                        ans += findCostPath(f);
                    }
                    else{
                        q.push(i);
                        viz[i] = true;
                    }
                }
            }
        }

        for(int i = 1; i <=n; i++){
            if(!viz[i]){
                if(graph[i][x].fSent > 0){
                    f[i] = -x;

                    if(i == n){
                        ans += findCostPath(f);
                    }
                    else{
                        q.push(i);
                        viz[i] = true;
                    }
                }
            }
        }

    }

   // cout << ans << " ";

    return ans;
}


int fluxMax(){

    int maxPush = 0;
    int ans = 0;
    do
    {
        maxPush = findPath();
        ans += maxPush;
        
    } while (maxPush);
    
    return ans;
}

int main()
{

    fin >> n >> m;

    for(int i = 1; i <= m; i++){
        fin >> x >> y >> cap;
        graph[x][y] = {cap, 0};
    }

    fout << fluxMax();

    return 0;
}