Description
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
Input
数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号。(0<=s,t<n)
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。(0<=a,b<n,a与b不相等,0<=c<=1000)
Output
只有一行,包含一个整数,为最少花费。
5 6 1 0 4 0 1 5 1 2 5 2 3 5 3 4 5 2 3 3 0 2 100
-
Sample Input
8
-
Sample Output
HINT
对于30%的数据,2<=n<=50,1<=m<=300,k=0;
对于50%的数据,2<=n<=600,1<=m<=6000,0<=k<=1;
对于100%的数据,2<=n<=10000,1<=m<=50000,0<=k<=10.
题目是多层图模板题,数据看起来不太大实则有点变态,而且刻意地卡了SPFA算法的最坏情况,所以这里用Dijkstra而不是SPFA(当然SPFA经过合理优化也能过)。建图就是把上层的from点和下层的to点之间连一条免费路,作为使用了一次白嫖机会,所以能白嫖一次就要多建一层图。注意数据范围要开够,不然有一个点会WA(我就是)。
#include<queue>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=110001,M=2500001;
struct Edge{
int nex,to,cost;
}edge[M];
int n,m,k,S,E;
int tot=0,headlist[N],d[N];
bool vis[N];
inline void adds(int x,int y,int w){//加边
edge[++tot].to=y;
edge[tot].cost=w;
edge[tot].nex=headlist[x];
headlist[x]=tot;
}
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline void Dijkstra(int x){
memset(d,0x3f3f3f3f,sizeof(d));
d[x]=0;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > points;//用优先队列维护
points.push(make_pair(0,x));
while(!points.empty())
{
int u=points.top().second;
points.pop();
if(!vis[u])
{
vis[u]=true;
for(int i=headlist[u];i;i=edge[i].nex)
{
int v=edge[i].to,w=edge[i].cost;
if(d[v]>d[u]+w)
{
d[v]=d[u]+w;
points.push(make_pair(d[v],v));
}
}
}
}
}
int main(){
n=read();m=read();k=read();S=read();E=read();
int x,y,w;
for(int i=1;i<=m;i++)
{
x=read();y=read();w=read();
adds(x,y,w);adds(y,x,w);
for(int j=1;j<=k;j++)
{
adds(x+(j-1)*n,y+j*n,0);
adds(y+(j-1)*n,x+j*n,0);//上层点与下层点相连,花费为0,表示可以白嫖
adds(x+j*n,y+j*n,w);//下层对应的点相连
adds(y+j*n,x+j*n,w);
}
}
for(int i=1;i<=k;i++)
adds(E+(i-1)*n,E+i*n,0);//为防止在免费次数花完前就到达上层终点,连一条把各层终点串起来的免费通路
Dijkstra(S);
printf("%d",d[E+k*n]);//输出最下层终点
return 0;
}
洛谷原题传送门:P4568 [JLOI2011]飞行路线