Cod sursa(job #1437298)

Utilizator crucerucalinCalin-Cristian Cruceru crucerucalin Data 17 mai 2015 14:19:31
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <limits>
#include <algorithm>

using FlowGraph = std::vector<std::vector<int>>;

const int NONE = -1;

std::vector<int>
bfsTree(
        const FlowGraph &graph,
        int source,
        int sink
)
{
    std::vector<int> parent(graph.size(), NONE);
    std::queue<int> bfsQueue;

    bfsQueue.emplace(source);
    while (!bfsQueue.empty()) {
        auto u = bfsQueue.front();

        bfsQueue.pop();
        for (auto v = 0; v < static_cast<int>(graph.size()); ++v)
            if (v != sink && graph[u][v] > 0 && parent[v] == NONE) {
                parent[v] = u;
                bfsQueue.emplace(v);
            }
    }

    return parent;
}

int
maxFlow(
        FlowGraph &graph,
        int source,
        int sink
)
{
    auto maxFlow = 0;

    while (true) {
        auto parentTree = bfsTree(graph, source, sink);
        auto newFlow = maxFlow;

        for (auto u = 0; u < static_cast<int>(graph.size()); ++u) {
            if (!graph[u][sink] || parentTree[u] == NONE)
                continue;

            auto v = u;
            auto w = sink;
            auto min = graph[v][w];

            do {
                w = v;
                v = parentTree[v];
                min = std::min(min, graph[v][w]);
            } while (v != source);

            newFlow += min;

            v = u;
            w = sink;
            while (w != source) {
                graph[v][w] -= min;
                graph[w][v] += min;

                w = v;
                v = parentTree[v];
            }
        }

        if (newFlow == maxFlow)
            break;
        else
            maxFlow = newFlow;
    }

    return maxFlow;
}

int main()
{
    std::ifstream fin{"maxflow.in"};
    std::ofstream fout{"maxflow.out"};

    int N, M;

    fin >> N >> M;
    FlowGraph graph(N, std::vector<int>(N, 0));

    for (auto i = 0; i < M; ++i) {
        int x, y, c;

        fin >> x >> y >> c;
        graph[x - 1][y - 1] = c;
    }

    fout << maxFlow(graph, 0, N - 1) << std::endl;

    return 0;
}