2763. [JLOI2011]飞行路线【分层图最短路】

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

只有一行,包含一个整数,为最少花费。

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.

分层图最短路,感觉有种DP的思想
dis多开一维表示第几层的点
每一层的最短路只能向当前层转移,代价为边长
或者向下一层转移,代价为0
最多有k次代价为0的转移,符合题意

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #define N (10000+100)
 6 using namespace std;
 7 int dis[12][N],n,m,k,s,t;
 8 int head[N],num_edge;
 9 bool used[12][N];
10 struct node1
11 {
12     int to,next,len;
13 }edge[N<<4];
14 struct node
15 {
16     int dep,num;
17 };
18 queue<node>q;
19 
20 void add(int u,int v,int l)
21 {
22     edge[++num_edge].to=v;
23     edge[num_edge].next=head[u];
24     edge[num_edge].len=l;
25     head[u]=num_edge;
26 }
27 
28 void Spfa()
29 {
30     memset(dis,0x7f,sizeof(dis));
31     dis[1][s]=0;
32     used[1][s]=true;
33     node x; x.dep=1; x.num=s;
34     q.push(x);
35     while (!q.empty())
36     {
37         node x=q.front(); q.pop();
38         for (int i=head[x.num];i!=0;i=edge[i].next)
39             for (int j=0;j<=1;++j)
40             {
41                 if (x.dep==k+1 && j==1) continue;
42                 if (dis[x.dep][x.num]+edge[i].len*(j^1)<dis[x.dep+j][edge[i].to])
43                 {
44                     dis[x.dep+j][edge[i].to]=dis[x.dep][x.num]+edge[i].len*(j^1);
45                     if (!used[x.dep+j][edge[i].to])
46                     {
47                         used[x.dep+j][edge[i].to]=true;
48                         node y; y.dep=x.dep+j; y.num=edge[i].to;
49                         q.push(y);
50                     }
51                 }
52                 
53             }
54         used[x.dep][x.num]=false;
55     }
56 }
57 
58 int main()
59 {
60     int u,v,l,ans=0x7fffffff;
61     scanf("%d%d%d%d%d",&n,&m,&k,&s,&t);
62     for (int i=1;i<=m;++i)
63     {
64         scanf("%d%d%d",&u,&v,&l);
65         add(u,v,l); add(v,u,l);
66     }
67     Spfa();    
68     for (int i=1;i<=k+1;++i)
69         ans=min(ans,dis[i][t]);
70     printf("%d",ans);
71 }
原文地址:https://www.cnblogs.com/refun/p/8682422.html