题意:求从城市1运送K单位物品到城市n的最小花费。给定的有向边,每条边都有其容量c,并且,产生的费用是 a * ( f * f ),其中f是这条边上的流量,a是给出的系数。
思路:我们以前做的 花费是 a*f ,而现在是 a*f*f。所以我们要变为 a*f
那么就是, 第一次运送时费用为a,第二次取这条路时费用为3a(即流量为2时费用值为a+3a=4a),……
第i次取这条路时费用为(2*i-1)*a
建图:u->v连c条边:(u, v, 1, (2 * i - 1) * a)
链接:hdu 3667
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <sstream>
#define INF 0x3f3f3f3f
using namespace std;
//最小费用最大流模版.求最大费用最大流建图时把费用取负即可。
//无向边转换成有向边时需要拆分成两条有向边。即两次加边。
const int maxn = 10005;
const int maxm = 3000200;
const int inf = 0x3f3f3f3f;
struct Edge {
int v, cap, cost, next;
}p[maxm << 1];
int e, sumFlow, n, m, sp, tp;
int head[maxn], dis[maxn], pre[maxn];
bool vis[maxn];
void init() {
e = 0;
memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int cap, int cost) {
p[e].v = v; p[e].cap = cap; p[e].cost = cost;
p[e].next = head[u]; head[u] = e++;
p[e].v = u; p[e].cap = 0; p[e].cost = -cost;
p[e].next = head[v]; head[v] = e++;
}
bool spfa(int s,int t) {
int u, v;
queue<int>q;
memset(vis, false, sizeof(vis));
memset(pre, -1, sizeof(pre));
memset(dis, inf, sizeof(dis));
vis[s] = true;
dis[s] = 0;
q.push(s);
while(!q.empty()) {
u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = p[i].next) {
v = p[i].v;
if(p[i].cap && dis[v] > dis[u] + p[i].cost) {
dis[v] = dis[u] + p[i].cost;
pre[v] = i;
if(!vis[v]) {
q.push(v);
vis[v] = true;
}
}
}
}
if(dis[t] == inf)
return false;
return true;
}
int MCMF(int s, int t) {
int flow = 0; // 总流量
int minflow, mincost;
mincost = 0;
while(spfa(s, t)) {
minflow = inf + 1;
for(int i = pre[t]; i != -1; i = pre[p[i^1].v]) {
if(p[i].cap < minflow) {
minflow = p[i].cap;
}
}
flow += minflow;
for(int i = pre[t]; i != -1; i = pre[p[i^1].v]) {
p[i].cap -= minflow;
p[i^1].cap += minflow;
}
mincost += dis[t] * minflow;
}
sumFlow = flow; // 最大流
return mincost;
}
int main ()
{
int t, kcase = 0;
int k;
while(~scanf("%d %d %d", &n, &m, &k) && n) {
init();
sp = 0, tp = n;
addEdge(sp, 1, k, 0);
int ui, vi, ai, ci;
for(int i = 0; i < m; i++) {
scanf("%d %d %d %d", &ui, &vi, &ai, &ci);
for(int j = 1; j <= ci; j++) {
addEdge(ui, vi, 1, (2 * j - 1) * ai);
}
}
int ans = MCMF(sp, tp);
if(sumFlow != k) {
ans = -1;
}
printf("%d\n", ans);
}
return 0;
}