Cod sursa(job #1520862)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 9 noiembrie 2015 17:25:58
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <tuple>
#include <queue>

using namespace std;

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

struct neighbour {
    int other;
    int i;
    int irev;
};
using graph = vector < vector < neighbour > >;

vector < neighbour > get_bftree(graph const &G, const int s, const int d, vector < int > const &cap) {
    vector < neighbour > parent(G.size());
    queue < int > q;
    int u;

    q.push(s);
    while(!q.empty() && q.front() != d) {
        u = q.front();
        q.pop();
        for(auto it : G[u]) if(cap[it.i] > 0) {
            if(parent[it.other].other == 0) {
                parent[it.other] = {u, it.i, it.irev};
                q.push(it.other);
            }
        }
    }

    return parent;
}

int augumentPath(graph const &G, vector < int > &cap, const int s, const int d) {
    vector < neighbour > tree = get_bftree(G, s, d, cap);
    if(tree[d].other == 0) return 0;
    int u, minval = 0x7fffffff;
    for(u = d; u != s; u = tree[u].other) {
        minval = min(minval, cap[tree[u].i]);
    }
    for(u = d; u != s; u = tree[u].other) {
        cap[tree[u].i] -= minval;
        cap[tree[u].irev] += minval;
    }
    return minval;
}

int edmonds_karp(graph const &G, const int s, const int d, vector < int > &cap) {
    int flow = 0, currFlow;
    do {
        currFlow = augumentPath(G, cap, s, d);
        flow += currFlow;
    } while(currFlow > 0);
    return flow;
}

int main() {
    int n, m, u, v, c, i;

    in >> n >> m;
    vector < int > cap(2*m);
    graph G(n + 1);
    for(i = 1; i <= m; i++) {
        in >> u >> v >> c;
        cap.push_back(c);
        cap.push_back(c);
        G[u].push_back(neighbour{v, cap.size() - 1, cap.size() - 2});
        G[v].push_back(neighbour{u, cap.size() - 2, cap.size() - 1});
    }

    out << edmonds_karp(G, 1, n, cap);
    return 0;
}