Cod sursa(job #2693064)

Utilizator CraniXortDumitrescul Eduard CraniXort Data 4 ianuarie 2021 18:05:56
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>

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

class Graph{
    private:
        int V;
        std::vector <std::vector <int>> edge;
        std::vector <std::vector <int>> cap;
        std::vector <int> parent;
        std::vector <bool> visited;

        int source, sink;

        bool bfs(){
            std::queue <int> q;
            q.push(source);
            std::fill(visited.begin(), visited.end(), false);
            visited[source] = true;

            while(q.empty() == false){
                int node = q.front();
                q.pop();
                if(node == sink)
                    continue;

                for(int next: edge[node]){
                    if(visited[next] == false and cap[node][next] > 0){
                        visited[next] = true;
                        q.push(next);
                        parent[next] = node;
                    }
                }
            }

            return visited[sink];
        }
    public:
        Graph(int size){
            V = size;
            edge.resize(V+1);
            cap.resize(V+1);
            for(auto& line: cap)
                line.resize(V+1);
            parent.resize(V+1);
            visited.resize(V+1);
        }

        void addEdge(int src, int dest, int capacity){
            edge[src].push_back(dest);
            edge[dest].push_back(src);
            cap[src][dest] = capacity;
        }

        int maxFlow(int src, int dest){
            source = src;
            sink = dest;
            int maxFlow = 0, flow;
            while(bfs()){
                flow = 1e9;
                for(int node: edge[sink]){
                    if(visited[node] == true and cap[node][sink] > 0){
                        parent[sink] = node;
                        for(int crt = sink; crt != source; crt = parent[crt])
                            flow = std::min(flow, cap[parent[crt]][crt]);
                        for(int crt = sink; crt != source; crt = parent[crt]){
                            cap[parent[crt]][crt] -= flow;
                            cap[crt][parent[crt]] += flow;
                        }
                    }
                    maxFlow += flow;
                }
            }
            return maxFlow;
        }
};

void readInput(){
    int V, E;
    fin >> V >> E;
    Graph graph(V);
    for(int i=0, src, dest, cap; i<E; i++){
        fin >> src >> dest >> cap;
        graph.addEdge(src, dest, cap);
    }
    fout << graph.maxFlow(1, V);
}

int main(){
    readInput();
    return 0;
}