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"

#define _USE_MATH_DEFINES
#include <cmath>
#include <cstdlib>
#include <deque>
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <iterator>

using namespace std;

#define rep(i,a,b) for(int i=(a), i##_len=(b);i<i##_len;i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)

//#define int long long
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair

typedef long long ll;
//typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<double, double> pdd;
typedef vector<vector<int>> mat;

template<class T> bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; }

const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;

#define VMAX 10010

struct edge
{
	int to, cap, cost, rev;
	edge(int to, int cap, int cost, int rev) :to(to), cap(cap), cost(cost), rev(rev) {}
	edge() :to(-1), cap(-1), cost(-1), rev(-1) {}
};

vector<edge> G[VMAX];
int h[VMAX], dist[VMAX], prevv[VMAX], preve[VMAX];
int V, E, F;

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));
}

int min_cost_flow(int s, int t, int f)
{
	int res = 0;
	fill(h, h + V, 0);
	while (f > 0)
	{
		priority_queue<pii, vector<pii>, greater<pii>> q;
		fill(dist, dist + V, INF);
		dist[s] = 0;
		q.push(pii(0, s));
		while (!q.empty())
		{
			pii p = q.top(); q.pop();
			int v = p.second;
			if (dist[v] < p.first)continue;
			rep(i, 0, SZ(G[v]))
			{
				edge& e = G[v][i];
				if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to])
				{
					dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
					prevv[e.to] = v;
					preve[e.to] = i;
					q.push(pii(dist[e.to], e.to));
				}
			}
		}
		if (dist[t] == INF)
		{
			return -1;
		}
		rep(v, 0, V)h[v] += dist[v];

		int d = f;
		for (int v = t; v != s; v = prevv[v])
		{
			chmin(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.rev].cap += d;
		}
	}
	return res;
}

int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);

	cin >> V >> E >> F;
	int s, t, c, d;
	rep(i, 0, E)
	{
		cin >> s >> t >> c >> d;
		add_edge(s, t, c, d);
	}

	cout << min_cost_flow(0, V - 1, F) << endl;

	return 0;
}