P4568 [JLOI2011]飞行路线
Description
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。
Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多kk种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
Input
- 数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号。
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。
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
Data Size
- 对于100%的数据,2≤n≤10000,1≤m≤50000,0≤k≤10,0≤s,t<n,0≤a,b<n,a≠b,0≤c≤1000
题解:
- 分层图最短路。
- 观察数据范围,k特别小(<=10)。所以可以用拆点的思想,就是把一个点拆成k种情况:用1次机会到达的、用2次机会到达的...用k次机会到达的。这样所有的状态就变成了一个大图。在这个大图上面跑最短路即可。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define N 100005
#define M 1000005
using namespace std;struct Node
{int val, pos;friend bool operator < (Node x, Node y) {return x.val > y.val;}
};
struct E {int next, to, dis;} e[M];
int n, m, k, s, t, num, ans = 0x7fffffff;
int h[N], dis[N];
bool vis[N]; int read()
{int x = 0; char c = getchar();while(c < '0' || c > '9') c = getchar();while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}return x;
}void add(int u, int v, int w)
{e[++num].next = h[u];e[num].to = v;e[num].dis = w;h[u] = num;
}void dijskra()
{memset(dis, 0x3f, sizeof(dis));priority_queue<Node> que;dis[s] = 0, que.push((Node){0, s});while(!que.empty()){int x = que.top().pos; que.pop();if(vis[x]) continue;vis[x] = 1;for(int i = h[x]; i != 0; i = e[i].next)if(dis[x] + e[i].dis < dis[e[i].to]){dis[e[i].to] = dis[x] + e[i].dis;if(!vis[e[i].to]) que.push((Node){dis[e[i].to], e[i].to});}}
}int main()
{cin >> n >> m >> k >> s >> t;s++, t++;for(int i = 1; i <= m; i++){int u = read() + 1, v = read() + 1, w = read();add(u, v, w), add(v, u, w);for(int j = 1; j <= k; j++){add(u + j * n, v + j * n, w);add(v + j * n, u + j * n, w);add(u + (j - 1) * n, v + j * n, 0);add(v + (j - 1) * n, u + j * n, 0);}}dijskra();for(int i = 0; i <= k; i++)ans = min(ans, dis[t + i * n]);cout << ans; return 0;
}