There are N cities, and M directed roads connecting them. Now you want to transport K 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 road i, there is a coefficient a
i. If you want to carry x units of goods along this road, you should pay a
i * x
2 dollars to hire guards to protect your goods. And what’s worse, for each road i, there is an upper bound C
i, which means that you cannot transport more than C
i 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.
You should find out the minimum cost to transport all the goods safely.
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
4 -1 3
题目大意:
有n个城市,m条道路,要从城市1运送k单位的货物到城市n,每条路有一个容量上限,路上有小偷,因此每条路上都有一个保障系数a,如果你想在某条路上ai运送x单位的货物,你要支付ai*x*x去雇佣保安来保护你的货物,现在给出m条道路连接的城市,保障系数,容量上限,问最少的花费是多少;
思路分析:
注意:这道题有一个很关键的条件,每条边的最大容量是5;
①:设立一个源点连向城市1,容量为1,费用为0;
②:对于每条给定的边,u,v,a,c,按照容量把边拆成c条边,每条边的容量为1,费用为(2*i-1)*c;
因为是平方关系,没有办法判断容量的分配,但是通过第一次走和第二次走费用等差,和一次走消耗相同来分配;
③:让城市n连向汇点,容量为1,费用为0;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 5e4+10;
const int M = 610;
int head[M], cnt;
struct node
{
int from, to, cap, cost, next;
}p[N];
void add(int u,int v,int w,int z)
{
p[cnt].from=u, p[cnt].to=v, p[cnt].cap=w, p[cnt].cost=z, p[cnt].next=head[u], head[u]=cnt++;
p[cnt].from=v, p[cnt].to=u, p[cnt].cap=0, p[cnt].cost=-z, p[cnt].next=head[v], head[v]=cnt++;
return ;
}
int d[M], pre[M], vis[M];
const int inf = 0x3f3f3f3f;
int min_cost_flow(int s,int t,int f)
{
int res=0;
while(f>0)
{
queue<int>q;
q.push(s);
fill(d,d+t+1,inf);
memset(pre,-1,sizeof(pre));
memset(vis,0,sizeof(vis));
vis[s]=1, d[s]=0;
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i!=-1;i=p[i].next)
{
int v=p[i].to;
if(d[v]>d[u]+p[i].cost&&p[i].cap>0)
{
d[v]=d[u]+p[i].cost;
pre[v]=i;
if(!vis[v])
{
q.push(v);
vis[v]=1;
}
}
}
vis[u]=0;
}
if(d[t]==inf) return -1;
int flow=f;
for(int i=pre[t];i!=s;i=pre[p[i].from])
{
flow=min(flow,p[i].cap);
}
res+=flow*d[t];
for(int i=pre[t];i!=s;i=pre[p[i].from])
{
p[i].cap-=flow, p[1^i].cap+=flow;
}
f-=flow;
}
return res;
}
int main()
{
int n, m, k;
while(scanf("%d %d %d", &n, &m, &k)!=EOF)
{
memset(head,-1,sizeof(head));
cnt=0;
int s=0, t=n+10;
add(s,1,k,0);
for(int i=0;i<m;i++)
{
int u, v, w, z;
scanf("%d %d %d %d", &u, &v, &w, &z);
for(int j=1;j<=z;j++)
{
add(u,v,1,w*(2*j-1));
}
}
add(n,t,k,0);
printf("%d\n",min_cost_flow(s,t,k));
}
return 0;
}