Cod sursa(job #2957513)

Utilizator GeorgeNistorNistor Gheorghe GeorgeNistor Data 22 decembrie 2022 19:05:34
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

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

int V, E, s, t;
vector<int> parrent;
vector<vector<long>> capacity;
//vector<vector<int>> adjList;
vector<vector<int>> adjListRes;

void init() {
    s = 1;
    t = V;
    //adjList.resize(V+1);
    adjListRes.resize(V+1);
    parrent.resize(V+1);
    capacity.resize(V+1, vector<long>(V+1));
}

void read(){
    fin >> V >> E;
    init();
    for(int i = 1; i <= E; i++){
        int u, v;
        long c;
        fin >> u >> v >> c;
        //adjList[u].push_back(v);

        adjListRes[u].push_back(v);
        adjListRes[v].push_back(u);

        capacity[u][v] = c;
        capacity[v][u] = 0;
    }
}

bool bfs(){
    vector<bool> visited(V+1);
    queue<int> q;

    q.push(s);
    visited[s] = true;
    parrent[s] = -1;

    while(!q.empty()){
        int u = q.front();
        q.pop();
        for(auto v: adjListRes[u]){
            if(!visited[v] and capacity[u][v]){
                parrent[v] = u;
                if(v == t)
                    return true;
                visited[v] = true;
                q.push(v);
            }
        }
    }
    return false;
}

int foldFulkerson(){

    int max_flow = 0;
    while(bfs()){
        int u, v, path_flow = INT_MAX;
        for(v = t; v != s; v = parrent[v]){
            u = parrent[v];
            if(capacity[u][v] < path_flow)
                path_flow = capacity[u][v];
        }
        for(v = t; v != s; v = parrent[v]){
            u = parrent[v];
            capacity[u][v] -= path_flow;
            capacity[v][u] += path_flow;
        }
        max_flow += path_flow;
    }
    return max_flow;
}

int main() {
    read();
    fout << foldFulkerson();
    return 0;
}