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;

struct edge
{
	int s, t, c, d,rev;
	edge(int s, int t, int c, int d,int rev) :s(s), t(t), c(c),d(d), rev(rev) {}
	edge() { s = -1, t = -1, c = -1, rev = -1; d = -1; }
};

vector<vector<edge>> G;
int dist[101];
int prevv[101], preve[101];

int min_cost_flow(int s, int t, int f)
{
	int res = 0;

	while (f > 0)
	{
		rep(i, 0, 101)dist[i] = INF;
		dist[s] = 0;
		while (true)
		{
			bool update = false;

			rep(i, 0, SZ(G))
			{
				if (dist[i] == INF)
				{
					continue;
				}
				rep(j, 0, SZ(G[i]))
				{
					edge e = G[i][j];
					if (e.c > 0 && dist[e.t] > dist[i] + e.d)
					{
						dist[e.t] = dist[i] + e.d;
						prevv[e.t] = i;
						preve[e.t] = j;
						update = true;
					}
				}
			}

			if (!update)
			{
				break;
			}
		}

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

		int tf = f;
		for (int i = t; i != s; i = prevv[i])
		{
			chmin(tf, G[prevv[i]][preve[i]].c);
		}
		f -= tf;
		res += tf*dist[t];
		for (int i = t; i != s; i = prevv[i])
		{
			G[prevv[i]][preve[i]].c -= tf;
			G[i][G[prevv[i]][preve[i]].rev].c += tf;
		}
	}

	return res;
}

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

	int V, E, F,s, t, c, d;
	cin >> V >> E >> F;
	G.resize(V);
	rep(i, 0, E)
	{
		cin >> s >> t >> c >> d;
		G[s].push_back(edge(s, t, c, d,SZ(G[t])));
		G[t].push_back(edge(t, s, 0, -d,SZ(G[s]) - 1));
	}

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

	return 0;
}