Description
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
Input
数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号.
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。(0<=a,b n,a与b不相等,0<=c<=1000)
Output
只有一行,包含一个整数,为最少花费。
Sample Input
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100
Sample Output
8
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.
标准的分层图题目,解决这种题目就是把图分成K层,对于一条边增加一个低层指向高层的边权值为0。注意如果是双向边,比如u-v,那么就u到高一层的v连一条边,v到高一层的u也连一条边.注意一定要是底层指向高层,不能有高层指向底层的边。具体看代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_V = 10010;
const int MAX_E = 50010;
const ll INF = 1e16+10;
class Edge{
public:
int to,nex;
ll cost;
Edge();
Edge(int _to,int _nex,ll _cost);
};
Edge edg[4*MAX_E*12];
int head[MAX_V*12],cnt;
ll dis[MAX_V*12];
void init(){
memset(head,-1,sizeof(head));
cnt = 0;
}
void add_Edge(int u,int v,ll w){
edg[cnt] = Edge(v,head[u],w);
head[u] = cnt++;
}
int N,M,K;
class Rule{
public:
bool operator() (const int A,const int B){
return dis[A] > dis[B];
}
};
void Dijkstra(int s,int t){
for(int i=0;i<=(K+1)*N;++i) dis[i] = INF;
priority_queue<int,vector<int>,Rule > que;
dis[s] = 0;
que.push(s);
while(!que.empty()){
int u = que.top();que.pop();
for(int i=head[u];~i;i=edg[i].nex){
Edge &e = edg[i];
if(dis[e.to] > dis[u] + e.cost){
dis[e.to] = dis[u] + e.cost;
que.push(e.to);
}
}
}
//遍历每一层的终点。
ll res = INF;
for(int i=0;i<=K;++i){
res = min(res,dis[t+i*N]);
}
printf("%lld\n",res);
}
int main(void){
int s,t;
init();
scanf("%d%d%d",&N,&M,&K);
scanf("%d%d",&s,&t);
int u,v;
ll w;
for(int i=1;i<=M;++i){
scanf("%d%d%lld",&u,&v,&w);
for(int l=0;l<=K;++l){
add_Edge(u+l*N,v+l*N,w);
add_Edge(v+l*N,u+l*N,w);
if(l != K){
//这里底层u连到高层v,和底层v连接高层u。永远是底层指向高层。
add_Edge(u+l*N,v+(l+1)*N,0);
add_Edge(v+l*N,u+(l+1)*N,0);
}
}
}
Dijkstra(s,t);
return 0;
}
Edge::Edge(){
to = nex = 0;
cost = 0;
}
Edge::Edge(int _to,int _nex,ll _cost){
to = _to;
nex = _nex;
cost = _cost;
}