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<algorithm>
#include<string>
#include<map>
#define _USE_MATH_DEFINES
#include<math.h>
#include<queue>
#include<deque>
#include<stack>
#include<cstdio>
#include<utility>
#include<set>
#include<list>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
#define FOR(i, a, b) for (ll i = (a); i <= (b); i++)
#define REP(i, n) FOR(i, 0, n - 1)
#define NREP(i, n) FOR(i, 1, n)
using ll = long long;
using pii = pair<int, int>;
using piii = pair<pii, pii>;
const ll dx[4] = { 0, -1, 1, 0 };
const ll dy[4] = { -1, 0, 0, 1 };
const int INF = 1e9 + 7;
int gcd(int x, int y) {
	if (x < y)swap(x, y);
	if (y == 0)return x;
	return gcd(y, x%y);
}
void mul(ll a, ll b) {
	a = a * b % INF;
}
double mysqrt(double x) {
	double l = 0, r = x;
	for (int i = 0; i < 64; ++i) {
		double m = (l + r) / 2.0;
		if (m*m < x)l = m;
		else r = m;
	}
	return l;
}
///////////////////////////////////////

//辺を表す構造体{行先、容量、コスト、逆辺}
struct edge { int to, cap, cost, rev; };
int V, E, F;
vector<edge>G[110];
int dist[110];
int prevv[110], preve[110];

void add_edge(int from, int to, int cap, int cost) {
	G[from].push_back(edge{ to, cap, cost, (int)G[to].size() });
	G[to].push_back(edge{ from,0,-cost,(int)G[from].size() - 1 });
}
//sからtへの流用fの最小費用流を求める
//流せない場合は-1を返す
int min_cost_flow(int s, int t, int f) {
	int res = 0;
	//ベルマンフォードによりs-t間最短路を求める
	while (f > 0) {
		fill(dist, dist + V, INF);
		dist[s] = 0;
		bool upgrade = true;
		while (upgrade) {
			upgrade = false;
			for (int v = 0; v < V; ++v) {
				if (dist[v] == INF)continue;
				for (int i = 0; i < G[v].size(); ++i) {
					edge &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;
						upgrade = 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]) {
			edge &e = G[prevv[v]][preve[v]];
			e.cap -= d;
			G[v][e.rev].cap += d;
		}
	}
	return res;
}

int main() {
	cin >> V >> E >> F;
	REP(i, E) {
		int from, to, cap, cost;
		cin >> from >> to >> cap >> cost;
		add_edge(from, to, cap, cost);
	}
	cout << min_cost_flow(0,V-1,F) << endl;
	return 0;
}