Cod sursa(job #2462901)

Utilizator preda.andreiPreda Andrei preda.andrei Data 27 septembrie 2019 23:41:47
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 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 dest, const vector<int> &pred)
{
    int next = dest;
    dest = pred[dest];

    int capacity = g[dest][next];
    while (dest != -1) {
        capacity = min(capacity, g[dest][next]);
        next = dest;
        dest = pred[dest];
    }
    return capacity;
}

void Flow(Graph &g, int dest, const vector<int> &pred, int capacity)
{
    int next = dest;
    dest = pred[dest];

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

        next = dest;
        dest = pred[dest];
    }
}

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

    while (FindPaths(g, source, dest, pred)) {
        auto capacity = FindCapacity(g, dest, pred);
        Flow(g, 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;
}