Problem: Examples

Input

4 5 2
0 1 2 1
0 2 1 2
1 2 1 1
1 3 1 3
2 3 2 1


Output

6


Input




Output

Solution (in CPP):

Solution:
#include <iostream>
#include <vector>
#include <numeric>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
using namespace std;

using Flow = int;

template<typename Flow = int>
struct PrimalDual {

    struct Edge {
        int dst;
        Flow cap, cap_orig;
        Flow cost;
        int revEdge; 
        bool isRev;
        Edge(int dst, Flow cap, Flow cost, int rev, bool isRev)
            :dst(dst), cap(cap), cap_orig(cap), cost(cost), revEdge(rev), isRev(isRev) {
        }
    };

    int n;
    vector<vector<Edge> > g;
    PrimalDual(int n_) : n(n_), g(vector<vector<Edge> >(n_)) {}
    void addEdge(int src, int dst, Flow cap, Flow cost) {
        g[src].emplace_back(dst, cap, cost, g[dst].size(), false);
        g[dst].emplace_back(src, 0, -cost, g[src].size() - 1, true);
    }
    Flow solve(int s, int t, int f) {
        constexpr Flow inf = numeric_limits<Flow>::max();
        Flow res = 0;
        vector<Flow> h(g.size()), dist(g.size());
        vector<int> prevv(g.size()), preve(g.size());
        while (f > 0) {
            priority_queue<pair<Flow, int>> q;
            fill(dist.begin(), dist.end(), inf);
            dist[s] = 0;
            q.emplace(0, s);
            while (q.size()) {
                int d, v;
                tie(d,v) = q.top();
                q.pop();
                d = -d;
                if (dist[v] < d) continue;
                for(int i = 0; i < (int)g[v].size(); ++i){
                    Edge &e = g[v][i];
                    if (e.cap > 0 && dist[e.dst] > dist[v] + e.cost + h[v] - h[e.dst]) {
                        dist[e.dst] = dist[v] + e.cost + h[v] - h[e.dst];
                        prevv[e.dst] = v;
                        preve[e.dst] = i;
                        q.emplace(-dist[e.dst], e.dst);
                    }
                }
            }
            if (dist[t] == inf) {
                return -1;
            }
            for (int i = 0; i < n; ++i) {
                h[i] += dist[i];
            }
            Flow d = f;
            for (int v = t; v != s; v = prevv[v]) {
                d = min(d, g[prevv[v]][preve[v]].cap);
            }
            f -= d;
            res += d * h[t];
            for (int v = t; v != s; v = prevv[v]) {
                Edge &e = g[prevv[v]][preve[v]];
                e.cap -= d;
                g[v][e.revEdge].cap += d;
            }
        }
        return res;
    }
};

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, m, f;
    cin >> n >> m >> f;
    PrimalDual<int> pd(n);
    for (int i = 0; i < m; i++) {
        int u, v, c, d;
        cin >> u >> v >> c >> d;
        pd.addEdge(u, v, c, d);
    }
    cout << pd.solve(0, n - 1, f) << endl;
}