Cod sursa(job #2961130)

Utilizator deboradeleanuDebora Deleanu deboradeleanu Data 5 ianuarie 2023 21:07:18
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector<vector<int>> graf, rgraf;
vector<int> parent;
int n, m, t, s, x, y, z;


void citire(){
    fin>>n>>m;
    s=1;
    t=n;

    graf.resize(n);
    parent.resize(n);
    rgraf.resize(n, vector<int>(n));

    for(int i=0; i<m; i++){
        fin >> x >> y >> z;
        graf[x].push_back(y);
        graf[y].push_back(x);
        rgraf[x][y]= z;
    }
}

bool bfs(){

    vector<bool> vizitat(n,false);
    queue<int> q;
    q.push(s);
    vizitat[s]= true;
    parent[s]=-1;

    while(!q.empty()){

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

        for(auto v: graf[u]) {
            if (vizitat[v] == false && rgraf[u][v] != 0) {
                parent[v] = u; //tine minte drumul
                if (v == t)
                    return true;
                vizitat[v] = true;
                q.push(v);

            }
        }
    }

    return false; //nu am gasit drum
}



int fordf(){

    int flowtotal= 0;
    while(bfs()){
        int u, v=t;
        int pathflow= INT_MAX;
        while(v != s){
            //parcurgem invers
            u = parent[v];
            //aflam bottleneckul
            if(rgraf[u][v] < pathflow)
                pathflow= rgraf[u][v];
            v = u;
        }
        v = t;
        while( v!= s ){
            u = parent[v];
            rgraf[u][v] -= pathflow;
            rgraf[v][u] += pathflow;
            v = u;
        }
        flowtotal += pathflow;
    }
    return flowtotal;

}


int main()
{
    citire();

    fout << fordf();

    return 0;
}