Cod sursa(job #2430965)

Utilizator ZanoxNonea Victor Zanox Data 17 iunie 2019 15:00:55
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <deque>
#include <climits>
#include <algorithm>

using namespace std;

struct Node {
    map<int, int> capacs;
};

struct Graph {
    int size;
    vector<Node> nodes;
};

vector<int> getBFSPath(Graph g, int source, int dest);

#define HAS(c, k) ((c).find(k) != (c).end())

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

    Graph g;
    int noEdges;
    fin>>g.size>>noEdges;
    g.nodes.resize(g.size + 1);

    for (int i = 0; i < noEdges; i++) {
        int a, b, c;
        fin>>a>>b>>c;

        g.nodes[a].capacs[b] = c;
        if (!HAS(g.nodes[b].capacs, a)) g.nodes[b].capacs[a] = 0;
    }

    int source = 1;
    int destination = g.size;

    vector<int> path = getBFSPath(g, source, destination);

    int flux = 0;

    while (!path.empty()) {
        int pathFlux = INT_MAX;
        for (int i = 0; i < path.size() - 1; i++) {
            int a = path[i];
            int b = path[i + 1];
            int c = g.nodes[a].capacs[b];

            pathFlux = min(pathFlux, c);
        }

        flux += pathFlux;

        for (int i = 0; i < path.size() - 1; i++) {
            int a = path[i];
            int b = path[i + 1];

            g.nodes[a].capacs[b] -= pathFlux;
            g.nodes[b].capacs[a] += pathFlux;
        }

        path = getBFSPath(g, 1, g.size);
    }

    fout<<flux<<'\n';
}

vector<int> getBFSPath(Graph g, int source, int sink) {
    deque<int> pq;
    vector<int> p(g.size + 1, 0);

    pq.push_back(source);

    while (!pq.empty()) {
        int n = pq.front();
        pq.pop_front();

        for (pair<int, int> it : g.nodes[n].capacs) {
            int dest = it.first;
            int c = it.second;
            if (!c) continue;
            if (p[dest]) continue;
            if (dest == source) continue;

            p[dest] = n;
            pq.push_back(dest);
        }
    }

    if (!p[sink]) return vector<int>();

    vector<int> sol;
    int n = sink;
    while (n) {
        sol.push_back(n);
        n = p[n];
    }

    reverse(sol.begin(), sol.end());

    return sol;
}