Cod sursa(job #2603147)

Utilizator melutMelut Zaid melut Data 18 aprilie 2020 17:26:35
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.64 kb
#include <fstream>
#include <vector>


using namespace std;


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


void Read(
    vector<vector<uint32_t>> &nodes,
    vector<vector<uint32_t>> &capacity
) {
    uint32_t n;
    uint32_t m;
    in >> n;
    in >> m;

    nodes.resize(n);
    capacity.resize(n, vector<uint32_t>(n));

    uint32_t node1;
    uint32_t node2;
    uint32_t cap;

    for (; m; --m) {
        in >> node1;
        in >> node2;
        in >> cap;

        --node1;
        --node2;

        nodes[node1].push_back(node2);
        nodes[node2].push_back(node1);
        capacity[node1][node2] = cap;
    }
}


inline bool DFS(
    vector<vector<uint32_t>> const &nodes,
    vector<vector<uint32_t>> const &capacity,
    vector<vector<int32_t>> &flow,
    vector<bool> &vis,
    vector<uint32_t> &parent,
    uint32_t &min_flow,
    uint32_t const node
) {
    vis[node] = true;

    if (node == nodes.size() - 1) {
        return true;
    }

    uint32_t neighbour;

    for (uint32_t i = 0; i < nodes[node].size(); ++i) {
        neighbour = nodes[node][i];

        if (!vis[neighbour])
        if (flow[node][neighbour] < capacity[node][neighbour]) {
            min_flow = min(min_flow, capacity[node][neighbour] - flow[node][neighbour]);
            parent[neighbour] = node;

            DFS(nodes, capacity, flow, vis, parent, min_flow, neighbour);
        }
    }

    return vis[nodes.size() - 1];
}


inline void Update(
    vector<vector<int32_t>> &flow,
    vector<uint32_t> const &parent,
    uint32_t const min_flow
) {
    for (uint32_t node = parent.size() - 1; node != 0; node = parent[node]) {
        flow[parent[node]][node] += min_flow;
        flow[node][parent[node]] -= min_flow;
    }
}


void Solve(
    vector<vector<uint32_t>> const &nodes,
    vector<vector<uint32_t>> const &capacity
) {
    vector<vector<int32_t>> flow(nodes.size(), vector<int32_t>(nodes.size()));
    vector<bool> vis(nodes.size());
    vector<uint32_t> parent(nodes.size());
    uint32_t min_flow = 0xffffffff;
    uint32_t sum_flow = 0;

    while (DFS(nodes, capacity, flow, vis, parent, min_flow, 0)) {
        if (min_flow == 0) {
            continue;
        }

        Update(flow, parent, min_flow);

        sum_flow += min_flow;
        min_flow = 0xffffffff;

        std::fill(vis.begin(), vis.end(), false);
    }

    out << sum_flow;
}


int main() {
    vector<vector<uint32_t>> nodes;
    vector<vector<uint32_t>> capacity;

    Read(nodes, capacity);

    Solve(nodes, capacity);

    in.close();
    out.close();

    return 0;
}