Cod sursa(job #2462909)

Utilizator preda.andreiPreda Andrei preda.andrei Data 27 septembrie 2019 23:58:15
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

struct Graph
{
    vector<vector<int>> edges;
    vector<vector<int>> capacity;

    Graph(int nodes) : edges(nodes), capacity(nodes, vector<int>(nodes, 0)) {}

    int Size() const { return edges.size(); }
};

bool FindPaths(const Graph &g, int source, int dest, vector<int> &pred)
{
    pred.assign(g.Size(), -1);

    vector<bool> visited(g.Size(), false);
    visited[source] = true;

    queue<int> q;
    q.push(source);

    while (!q.empty()) {
        auto node = q.front();
        q.pop();

        for (const auto &next : g.edges[node]) {
            if (g.capacity[node][next] > 0 && !visited[next]) {
                pred[next] = node;
                visited[next] = true;
                q.push(next);
            }
        }
    }
    return visited[dest];
}

int FindCapacity(const Graph &g, int node, int next, const vector<int> &pred)
{
    int capacity = g.capacity[node][next];
    while (node != -1) {
        capacity = min(capacity, g.capacity[node][next]);
        next = node;
        node = pred[node];
    }
    return capacity;
}

void Flow(Graph &g, int node, int next, const vector<int> &pred, int capacity)
{
    if (capacity <= 0) {
        return;
    }

    while (node != -1) {
        g.capacity[node][next] -= capacity;
        g.capacity[next][node] += capacity;

        next = node;
        node = pred[node];
    }
}

int MaxFlow(Graph &g, int source, int dest)
{
    vector<int> pred(g.Size(), -1);
    int flow = 0;

    while (FindPaths(g, source, dest, pred)) {
        for (int i = 0; i < g.Size(); i += 1) {
            if (g.capacity[i][dest] > 0) {
                int capacity = FindCapacity(g, i, dest, pred);
                Flow(g, i, dest, pred, capacity);
                flow += capacity;
            }
        }
    }
    return flow;
}

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

    int nodes, edges;
    fin >> nodes >> edges;

    Graph graph(nodes);
    for (int i = 0; i < edges; i += 1) {
        int a, b, capacity;
        fin >> a >> b >> capacity;
        graph.edges[a - 1].push_back(b - 1);
        graph.edges[b - 1].push_back(a - 1);
        graph.capacity[a - 1][b - 1] = capacity;
    }

    auto flow = MaxFlow(graph, 0, nodes - 1);
    fout << flow << "\n";

    return 0;
}