There are N cities, and M directed roads connecting them. Now you want to transportK units of goods from city 1 to city N. There are many robbers on the road, so you must be very careful. The more goods you carry, the more dangerous it is. To be more specific, for each roadi, there is a coefficient ai. If you want to carryx units of goods along this road, you should pay ai* x2 dollars to hire guards to protect your goods. And what's worse, for each roadi, there is an upper bound Ci, which means that you cannot transport more thanCi units of goods along this road. Please note you can only carry integral unit of goods along each road.
You should find out the minimum cost to transport all the goods safely.
Input
There are several test cases. The first line of each case contains three integers,N, M and K. (1N
100, 1
M
5000, 0
K
100). Then M lines followed, each contains four integers (ui,vi, ai, Ci), indicating there is a directed road from cityui to vi, whose coefficient isai and upper bound is Ci.(1
ui,vi
N, 0 <ai
100,Ci
5)
Output
Output one line for each test case, indicating the minimum cost. If it is impossible to transport all theK units of goods, output `-1'.
Sample Input
2 1 2 1 2 1 2 2 1 2 1 2 1 1 2 2 2 1 2 1 2 1 2 2 2
Sample Output
4 -1 3
#include<iostream>
#include<cstring>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 110;
const int inf = 1e9;
int n , m , k;
int d[maxn] , a[maxn];
bool inq[maxn];
int p[maxn];
struct Edge
{
int u , v , cost;
int flow , cap;
Edge(int uu,int vv,int cost,int flow,int cap)
: u(uu) , v(vv) , cost(cost) , flow(flow) , cap(cap) { }
};
vector<Edge> edge;
vector<int> G[maxn];
void add(int s,int t,int cap,int cost)
{
edge.push_back(Edge(s,t,cost,0,cap));
edge.push_back(Edge(t,s,-cost,0,0));
int x = edge.size();
G[s].push_back(x-2);
G[t].push_back(x-1);
}
int cap[] = { 0,1,3,5,7,9 };
void input()
{
edge.clear();
for (int i = 0 ; i < n+1 ; ++i) G[i].clear();
add(0,1,k,0);
int u , v , a , c;
while (m--) {
scanf("%d%d%d%d",&u,&v,&a,&c);
for (int i = 1 ; i <= c ; ++i)
add(u,v,1,a*cap[i]);
}
}
bool spfa(int s,int t,int &flow,int &cost)
{
memset(inq,false,sizeof(inq));
for (int i = 0 ; i <= n ; ++i) d[i] = a[i] = inf;
queue<int> q;
q.push(s);
d[s] = 0; inq[s] = false;
while (q.size()) {
int u = q.front(); q.pop();
inq[u] = false;
for (int i = 0 ; i < G[u].size() ; ++i) {
Edge & e = edge[G[u][i]];
if (e.cap > e.flow && d[e.v] > d[u]+e.cost) {
d[e.v] = d[u] + e.cost;
p[e.v] = G[u][i];
a[e.v] = min(a[u],e.cap-e.flow);
if (!inq[e.v]) { inq[e.v] = true; q.push(e.v); }
}
}
}
if (d[t]==inf) return false;
flow += a[t];
cost += a[t]*d[t];
int x = t;
while (x!=s) {
edge[p[x]].flow += a[t];
edge[p[x]^1].flow -= a[t];
x = edge[p[x]].u;
}
return true;
}
int mincost(int s,int t)
{
int flow = 0 , cost = 0;
while (spfa(s,t,flow,cost));
if (flow < k) return -1;
return cost;
}
int main()
{
while (scanf("%d%d%d",&n,&m,&k)==3)
{
input();
printf("%d\n",mincost(0,n));
}
}