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 INF 1e9
#define llINF 1e18
#define MOD 1000000007
#define pb push_back
#define mp make_pair 
#define F first
#define S second
#define ll long long
#define ull unsigned long long
#define vi vector<ll>
#define vvi vector<vi>
#define BITLE(n) (1LL<<((ll)n))
#define BITCNT(n) (__builtin_popcountll(n))
#define SUBS(s,f,t) ((s).substr((f)-1,(t)-(f)+1))
#define ALL(a) (a).begin(),(a).end()
using namespace std;
struct MinCostFlow{
  struct edge{
    ll to,cap,cost,rev;
  };
  const ll MAX_V=200100;
  const ll Inf=1e18;
  ll V;
  vector<vector<edge>>E;
  vi dist,h,prevv,preve;
  MinCostFlow(ll V):V(V),E(V),dist(V),h(V),prevv(V),preve(V){}

  void addEdge(ll from, ll to, ll cap, ll cost){
    E[from].pb({to,cap,cost,(ll)E[to].size()});
    E[to].pb({from,0,-cost,(ll)E[from].size()-1});
  }

  void dijkstra(ll s){
    priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>>que;
    fill(ALL(dist),Inf);
    dist[s] = 0;
    que.push(pair<ll,ll>(0,s));
    while(!que.empty()){
      pair<ll,ll> p = que.top();
      que.pop();
      ll v = p.second;
      if(dist[v] < p.first)continue;
      for(int j = 0;j < E[v].size();j++){
	edge t = E[v][j];
	if(t.cap > 0&&dist[t.to] > dist[v] + t.cost + h[v] - h[t.to]){
	  dist[t.to] = dist[v] + t.cost + h[v] - h[t.to];
	  prevv[t.to] = v;preve[t.to] = j;
	  que.push(pair<ll,ll>(dist[t.to],t.to));
	}
      }
    }
  }

  ll execution(ll s,ll t,ll f){
    ll ret = 0;
    fill(ALL(h),0);
    while(f>0){
      dijkstra(s);
      if(dist[t] == Inf)return -1;
      for(ll v = 0;v < V;v++)h[v] += dist[v];

      ll d = f;
      for(ll v = t; v != s; v = prevv[v]){
	d = min(d, E[prevv[v]][preve[v]].cap);
      }
      f -= d;
      ret += d * h[t];
      for(int v = t; v != s; v = prevv[v]){
	edge &e = E[prevv[v]][preve[v]];
	e.cap -= d;
	E[v][e.rev].cap += d;
      }
    }
    return ret;
  }
};

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll v,e,f;cin>>v>>e>>f;
  MinCostFlow mcf(v);
  for(int i=0;i<e;i++){
    ll f,t,c,d;cin>>f>>t>>c>>d;
    mcf.addEdge(f,t,c,d);
  }
  cout<<mcf.execution(0,v-1,f)<<endl;
  return 0;
}