西北大学:西湖奇遇记Ⅰ【最短路】
传送门
看代码更容易理解
///#include<bits/stdc++.h>
///#include<unordered_map>
///#include<unordered_set>
#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#define MT(a, b) memset(a,b,sizeof(a)
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double pai = acos(-1.0);
const double E = 2.718281828459;
const ll mod = 998244353;
const ll INF = 0x3f3f3f3f3f3f;
const int maxn = 1e6 + 5;
ll dis[maxn][6];
struct node {
int e;
ll c;
int p;
bool friend operator<(node a, node b) {
return a.c > b.c;
}
} load[maxn << 1];
int head[maxn], sign;
void add_edge(int s, int e, ll c) {
load[++sign] = node{e, c, head[s]};
head[s] = sign;
}
void init() {
sign = 0;
memset(dis, 127, sizeof(dis));
memset(head, -1, sizeof(head));
}
int main() {
init();
int n, m, k, s, e, t;
ll c;
scanf("%d %d %d", &n, &m, &k);
while (m--) {
scanf("%d %d %lld", &s, &e, &c);
add_edge(s, e, c);
add_edge(e, s, c);
}
dis[1][0] = 0;
priority_queue<node> q;
q.push(node{1, 0, 0});
///e:到达的终点 c:距离起点的花费 p:乘坐缆车的次数
while (!q.empty()) {
node w = q.top();
q.pop();
s = w.e, t = w.p;///t 已经乘坐缆车的次数
if (w.e == n) {
printf("%lld\n", w.c);
break;
}
for (int i = head[s]; ~i; i = load[i].p) {
e = load[i].e;
c = load[i].c;
if (dis[e][t] > w.c + c) { ///不坐缆车
dis[e][t] = w.c + c;
q.push(node{e, dis[e][t], t});
}
if (t < k && dis[e][t + 1] > w.c + 1) { ///坐缆车
dis[e][t + 1] = w.c + 1;
q.push(node{e, dis[e][t + 1], t + 1});
}
}
}
return 0;
}