题意:有N个节点M条边的有向图,现在你需要从1号节点运送k个货物到N号节点. 每条边都有一个ai和ci值,ci值是指该边最多能运ci个货物,而你如果在该边运x(1<=x<=ci)个货物需要花费ai*x*x代价.问你运送这k个货物的最小代价是多少?
思路:这里显然是最小费用最大流的问题,问题是每条边的权值为一个函数,大白书上有讲,举个例子,比如最多能运4个货物,那么在该边分别运1,2,3,4个货物的代价就是ai*1,ai*4,ai*9,ai*16,那么相减一下有ai*1,ai*3,ai*5,ai*7,显然运送几个货物的代价就是这个等差数列的前n项和,那么把最多可以运送c件货物拆成c条边,每条边容量为1,权值为ai*(2*i-1),这样费用流的时候第一次就会选权值最小的那条边,第二次就会选次小的那条边,把结果累加就是前n项和了,非常巧妙的拆边建图。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#define INF 1e9
using namespace std;
const int maxn=100+5;
struct Edge
{
int from,to,cap,flow,cost;
Edge(){}
Edge(int f,int t,int c,int fl,int co):from(f),to(t),cap(c),flow(fl),cost(co){}
};
struct MCMF
{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool inq[maxn];
int d[maxn];
int a[maxn];
int p[maxn];
void init(int n,int s,int t)
{
this->n=n, this->s=s, this->t=t;
edges.clear();
for(int i=0;i<n;++i) G[i].clear();
}
void AddEdge(int from,int to,int cap,int cost)
{
edges.push_back(Edge(from,to,cap,0,cost));
edges.push_back(Edge(to,from,0,0,-cost));
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(int &flow,int &cost)
{
queue<int> Q;
for(int i=0;i<n;++i) d[i]=INF;
memset(inq,0,sizeof(inq));
d[s]=0,a[s]=INF,p[s]=0,inq[s]=true,Q.push(s);
while(!Q.empty())
{
int u=Q.front(); Q.pop();
inq[u]=false;
for(int i=0;i<G[u].size();++i)
{
Edge &e=edges[G[u][i]];
if(e.cap>e.flow && d[e.to]>d[u]+e.cost)
{
d[e.to] = d[u]+e.cost;
a[e.to] = min(a[u],e.cap-e.flow);
p[e.to] = G[u][i];
if(!inq[e.to]) {inq[e.to]=true; Q.push(e.to);}
}
}
}
if(d[t]==INF) return false;
flow += a[t];
cost += d[t]*a[t];
int u=t;
while(u!=s)
{
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -=a[t];
u = edges[p[u]].from;
}
return true;
}
int solve(int k)
{
int flow=0,cost=0;
while(BellmanFord(flow,cost));
return flow==k? cost:-1;
}
}MM;
int main()
{
int n,m,k;
while(scanf("%d%d%d",&n,&m,&k)==3)
{
int src=0,dst=n;
MM.init(n+1,src,dst);
MM.AddEdge(src,1,k,0);
while(m--)
{
int u,v,a,c;
scanf("%d%d%d%d",&u,&v,&a,&c);
for(int i=1;i<=c;++i)
MM.AddEdge(u,v,1,a*(2*i-1));
}
printf("%d\n",MM.solve(k));
}
return 0;
}