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 <utility>
#include <queue>
#define llint long long
#define inf 1e18

using namespace std;
typedef pair<llint, llint> P;

struct edge{
	llint to, cap, cost, rev;
	edge(){}
	edge(llint a, llint b, llint c, llint d){
		to = a, cap = b, cost = c, rev = d;
	}
};

llint n, m, F;
llint S, T;
vector<edge> G[205];
llint dist[205];
llint prevv[205], preve[205];
llint h[205];

void BellmanFord()
{
	for(int i = 0; i <= T; i++) dist[i] = inf;
	dist[S] = 0, prevv[S] = -1;
	
	bool update = true;
	while(update){
		update = false;
		for(int i = 0; i <= T; i++){
			for(int j = 0; j < G[i].size(); j++){
				if(G[i][j].cap == 0) continue;
				if(dist[G[i][j].to] > dist[i] + G[i][j].cost){
					dist[G[i][j].to] = dist[i] + G[i][j].cost;
					prevv[G[i][j].to] = i;
					preve[G[i][j].to] = j;
					update = true;
				}
			}
		}
	}
}

void Dijkstra()
{
	for(int i = 0; i <= T; i++) dist[i] = inf;
	dist[S] = 0, prevv[S] = -1;
	
	priority_queue< P, vector<P>, greater<P> > Q;
	Q.push( make_pair(0, S) );
	
	llint v, d;
	while(Q.size()){
		d = Q.top().first;
		v = Q.top().second;
		Q.pop();
		if(dist[v] < d) continue;
		for(int i = 0; i < G[v].size(); i++){
			if(G[v][i].cap == 0) continue;
			llint u = G[v][i].to, c = h[v] - h[u] + G[v][i].cost;
			if(dist[u] > d + c){
				dist[u] = d + c;
				prevv[u] = v;
				preve[u] = i;
				Q.push( make_pair(dist[u], u) );
			}
		}
	}
}

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


int main()
{
	cin >> n >> m >> F;
	llint u, v, c, d;
	for(int i = 1; i <= m; i++){
		cin >> u >> v >> c >> d;
		add_edge(u, v, c, d);
	}
	S = 0, T = n-1;
	
	BellmanFord();
	for(int i = 0; i <= T; i++) h[i] = dist[i];
	
	llint f = F, ans = 0;
	while(f > 0){
		Dijkstra();
		if(dist[T] >= inf) break;
		
		llint p = T, flow = f;
		while(prevv[p] != -1){
			flow = min(flow, G[prevv[p]][preve[p]].cap);
			p = prevv[p];
		}
		
		p = T;
		while(prevv[p] != -1){
			G[prevv[p]][preve[p]].cap -= flow;
			G[p][G[prevv[p]][preve[p]].rev].cap += flow;
			p = prevv[p];
		}
		f -= flow;
		ans += (dist[T] + h[T] - h[S]) * flow;
		
		for(int i = 0; i <= T; i++) h[i] += dist[i];
	}
	
	if(f > 0) ans = -1;
	cout << ans << endl;
	
	return 0;
}