分析:
给出N个城市,M条路,K个货物,每条路的费用系数 ai 和最大运送数量C,求把K个货物从城市1运送到N需要的最小费用,每条路的费用为一个系数 ai 乘以在这条路上运送的货物数量的平方。一看便是一个最大流最小费用,不过费用为动态的,所以我们可以采用拆边的方法,把动态的费用变成静态的边。题解
1.拆边方法:
把 ai×X2 (X表示第i条路上的货物)拆成C条路(C条路费用和 为 最大运输量时的最大费用):
scanf("%d%d%d%d", &u, &v, &a, &c);
for(int j=1;j<=c;j++)
Add(u,v,1, a*(2*j-1)); //拆成C条路
2.SPFA遍历出最小花费:
bool vis[MaxN];
int dist[MaxN];
int pre[MaxN];
int s,t,aug;
int ans;
int KK;
bool SPFA()
{
int k,p,V;
queue <int> q;
MST(pre,-1);
CLR(vis);
for(int i=0;i<=n;i++)
dist[i] = INF;
q.push(s);
vis[s] = 1;
dist[s] = 0;
while(!q.empty())//寻找最短路
{
k = q.front();
q.pop();
vis[k] = 0;
for(p = head[k]; p!=-1; p=edge[p].next)
{
V = edge[p].v;
if(edge[p].flow && (edge[p].cost + dist[k] < dist[V]))
{
dist[V] = edge[p].cost + dist[k];
pre[V] = p;
if(!vis[V])
{
q.push(V);
vis[V] = 1;
}
}
}
}
if(dist[t] == INF) return false;
aug =INF+1;
for(p = pre[t]; p!= -1; p = pre[edge[p].u])//沿着增广路走一遍
{
aug = min(aug, edge[p].flow);
}
for(p=pre[t]; p!= -1; p = pre[edge[p].u])//更新残余网络
{
edge[p].flow -= aug;
edge[p^1].flow += aug;
}
ans += dist[t]*aug;
KK += aug;
return true;
}
- AC代码:
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#define CLR(a) memset(a,0,sizeof(a))
#define MST(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MaxN = 105;
const int MaxM = MaxN*5000;
const int INF = 10000000;
int N,M,K;
struct node
{
int u,v,flow,cost;
int next;
}edge[MaxM];
int cont;
int head[MaxN];
int n;//node numbers
void add(int u, int v, int flow, int cost)
{
edge[cont].u = u;
edge[cont].v = v;
edge[cont].flow = flow;
edge[cont].cost = cost;
edge[cont].next = head[u];
head[u] = cont++;
}
void Add(int u, int v, int flow , int cost)
{
add(u,v,flow,cost);
add(v,u,0,-cost);
}
void init()
{
memset(head, -1,sizeof(head));
cont = 0;
n = 0;
}
bool vis[MaxN];
int dist[MaxN];
int pre[MaxN];
int s,t,aug;
int ans;
int KK;
bool SPFA()
{
int k,p,V;
queue <int> q;
MST(pre,-1);
CLR(vis);
for(int i=0;i<=n;i++)
dist[i] = INF;
q.push(s);
vis[s] = 1;
dist[s] = 0;
while(!q.empty())
{
k = q.front();
q.pop();
vis[k] = 0;
for(p = head[k]; p!=-1; p=edge[p].next)
{
V = edge[p].v;
if(edge[p].flow && (edge[p].cost + dist[k] < dist[V]))
{
dist[V] = edge[p].cost + dist[k];
pre[V] = p;
if(!vis[V])
{
q.push(V);
vis[V] = 1;
}
}
}
}
if(dist[t] == INF) return false;
aug =INF+1;
for(p = pre[t]; p!= -1; p = pre[edge[p].u])
{
aug = min(aug, edge[p].flow);
}
for(p=pre[t]; p!= -1; p = pre[edge[p].u])
{
edge[p].flow -= aug;
edge[p^1].flow += aug;
}
ans += dist[t]*aug;
KK += aug;
return true;
}
int main()
{
while(~scanf("%d%d%d", &N, &M, &K))
{
init();
s=0;
t=N;
for(int i=0;i<M;i++)
{
int u,v,a,c;
scanf("%d%d%d%d", &u, &v, &a, &c);
for(int j=1;j<=c;j++)
Add(u,v,1, a*(2*j-1));
}
Add(s,1,K,0);
n = N;
ans = 0;
KK=0;
while(SPFA());
if(KK < K) ans = -1;
cout << ans << endl;
}
return 0;
}