Cod sursa(job #2462906)

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

using namespace std;

using Graph = vector<vector<int>>;

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 (size_t i = 0; i < g.size(); i += 1) {
            if (g[node][i] > 0 && !visited[i]) {
                pred[i] = node;
                visited[i] = true;
                q.push(i);
            }
        }
    }
    return visited[dest];
}

int FindCapacity(const Graph &g, int node, int next, const vector<int> &pred)
{
    int capacity = g[node][next];
    while (node != -1) {
        capacity = min(capacity, g[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[node][next] -= capacity;
        g[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 (size_t i = 0; i < g.size(); i += 1) {
            if (g[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, vector<int> (nodes, 0));
    for (int i = 0; i < edges; i += 1) {
        int a, b, capacity;
        fin >> a >> b >> capacity;
        graph[a - 1][b - 1] = capacity;
    }

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

    return 0;
}