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 <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i, a, b) for (int i = (a); i < (int)(b); ++i)
#define rrep(i, a, b) for (int i = (int)(b) - 1; i >= (int)(a); --i)
#define all(c) c.begin(),c.end()
#define sz(x) ((int)x.size())
using pii = pair<int, int>;
using vvi = vector<vector<int>>;
using vi  = vector<int>;
constexpr int INF = 1001001001001001001LL;

struct MinCostFlow {
    struct edge { int to, cap, cost, rev; };
    int V;
    vector<vector<edge>> G;
    vi dist, prevv, preve;

    MinCostFlow(int V) : V(V), G(V), dist(V), prevv(V), preve(V) {}

    void add_edge(int from, int to, int cap, int cost) {
        G[from].push_back((edge){ to,   cap, cost, sz(G[to])       });
        G[to  ].push_back((edge){ from, 0,  -cost, sz(G[from]) - 1 });
    }

    // 流せない場合は-1を返す
    int get(int s, int t, int f) {
        int res = 0;
        while (f > 0) {
            fill(all(dist), INF);
            dist[s] = 0;
            bool update = true;
            while (update) {
                update = false;
                rep(v, 0, V) {
                    if (dist[v] == INF) continue;
                    rep(i, 0, sz(G[v])) {
                        auto &e = G[v][i];
                        if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
                            dist[e.to] = dist[v] + e.cost;
                            prevv[e.to] = v;
                            preve[e.to] = i;
                            update = true;
                        }
                    }
                }
            }

            if (dist[t] == INF) {
                return -1;
            }

            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 * dist[t];
            for (int v = t; v != s; v = prevv[v]) {
                auto &e = G[prevv[v]][preve[v]];
                e.cap -= d;
                G[v][e.rev].cap += d;
            }
        }
        return res;
    }
};

signed main() {
    int V, E, F;
    cin >> V >> E >> F;
    MinCostFlow min_cost_flow(V);
    rep(i, 0, E) {
        int vs, vt, cap, cost;
        cin >> vs >> vt >> cap >> cost;
        min_cost_flow.add_edge(vs, vt, cap, cost);
    }
    cout << min_cost_flow.get(0, V - 1, F) << endl;
}