Files
python/TangDou/AcWing/MiniPath/P4568_1.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

74 lines
2.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 * 2 * 11 + 10; //节点数:1e4,无向图,1e4*2,共k+1(k<=10)层:1e4*2*11
const int M = 5e4 * 11 * 3 + 10; //边数
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
int dist[N], st[N];
//邻接表
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int n, m, s, t, k;
void dijkstra() {
priority_queue<PII, vector<PII>, greater<PII>> q;
dist[s] = 0;
q.push({0, s});
while (q.size()) {
int u = q.top().second;
q.pop();
if (st[u]) continue;
st[u] = true;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (st[j]) continue;
if (dist[j] > dist[u] + w[i]) {
dist[j] = dist[u] + w[i];
q.push({dist[j], j});
}
}
}
}
int main() {
//多组测试数据
while (~scanf("%d%d%d", &n, &m, &k)) {
//初始化
memset(h, -1, sizeof(h));
idx = 0;
memset(dist, 0x3f, sizeof(dist));
memset(st, false, sizeof(st));
scanf("%d%d", &s, &t); //起点与终点
while (m--) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
//分层图建图
for (int i = 0; i <= k; i++) { //创建k+1层分层图
add(a + i * n, b + i * n, c), add(b + i * n, a + i * n, c); //无向图
if (i < k) //从第0层开始,到k-1层结束,都需要向下一层建立通道
add(a + i * n, b + (i + 1) * n, 0), add(b + i * n, a + (i + 1) * n, 0);
}
}
//一遍最短路
dijkstra();
// k+1个层中,都去找t的最短路径,再取最小值,就是答案
int ans = INF;
for (int i = 0; i <= k; i++)
ans = min(ans, dist[t + i * n]);
printf("%d\n", ans);
}
return 0;
}