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;

const int MAX_V = 100010;
using Flow = int;
const auto inf = numeric_limits<Flow>::max() / 8;
struct Edge {
    int dst;
    Flow cap, cap_orig;
    Flow cost;
    int revEdge; bool isRev;
    Edge(int dst, Flow cap, Flow cost, int revEdge, bool isRev)
        :dst(dst), cap(cap), cap_orig(cap), cost(cost), revEdge(revEdge), isRev(isRev) {
    }
};
struct PrimalDual {
    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) {
        Flow res = 0;
        vector<Flow> h(g.size()), dist(g.size());
        vector<int> prevv(g.size()), preve(g.size());
        while (f > 0) {
            using State = pair<Flow, int>;
            priority_queue<State, vector<State>, greater<State> > q;
            fill(dist.begin(), dist.end(), inf);
            dist[s] = 0;
            q.emplace(0, s);
            while (q.size()) {
                State p = q.top(); q.pop();
                int v = p.second;
                if (dist[v] < p.first) 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];
            }
            int 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 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;
}