Cod sursa(job #2407618)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 17 aprilie 2019 01:41:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <bits/stdc++.h>

int N, M;
std::vector <std::vector <int>> cap, graph;

inline void addEdge(int x, int y, int c) {
    graph[x].push_back(y);
    graph[y].push_back(x);
    cap[x][y] = c;
}

class EdmondKarp {
public:
    EdmondKarp(std::vector <std::vector <int>>& graph, std::vector <std::vector <int>> cap, int S, int T) : S(S), T(T), flowValue(0) {
        seen.resize(graph.size());
        parent.resize(graph.size());
        flow.resize(graph.size(), std::vector <int> (graph.size(), 0));
        this->graph = &graph;
        this->cap = &cap;

        while (BFS()) {
            for (auto adj:graph[T]) if (seen[adj] && flow[adj][T] != cap[adj][T]) {
                parent[T] = adj;
                int min = cap[adj][T] - flow[adj][T];
                int x = T;
                while (x != S)
                    min = std::min(min, cap[parent[x]][x] - flow[parent[x]][x]), x = parent[x];
                if (min == 0) continue;
                x = T;
                while (x != S)
                    flow[parent[x]][x] += min, flow[x][parent[x]] -= min, x = parent[x];
                flowValue += min;
            }
        }
    }

    inline int getMaxFlow() {return flowValue;}

private:
    int S, T, flowValue;
    std::queue <int> queue;
    std::vector <int> parent;
    std::vector <bool> seen;
    std::vector <std::vector <int>> flow, *graph, *cap;
    bool BFS() {
        for (int i=0; i<graph->size(); ++i)
            seen[i] = 0;
        queue.push(S), seen[S] = 0;
        int front;
        while (!queue.empty()) {
            front = queue.front();
            queue.pop();
            if (front == T) continue;
            for (auto adj:((*graph)[front]))
                if (!seen[adj] && flow[front][adj] != (*cap)[front][adj])
                    queue.push(adj), seen[adj] = 1, parent[adj] = front;
        }   return seen[T];
    }
};

std::ifstream input ("maxflow.in");
std::ofstream output("maxflow.out");

void readInput() {
    input >> N >> M;
    cap.resize(N+1, std::vector <int> (N+1, 0));
    graph.resize(N+1);
    for (int i=1, x, y, c; i<=M; ++i)
        input >> x >> y >> c, addEdge(x, y, c);
}

void solveInput() {
    output << (EdmondKarp(graph, cap, 1, N)).getMaxFlow();
}

int main()
{
    readInput();
    solveInput();

    return 0;
}