You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 2510;
const int M = 6200 * 2 + 10;
typedef pair<int, int> PII;
// 邻接表
int h[N], w[M], e[M], ne[M], idx;
bool st[N]; // 是否使用过
int d[N]; // 最短距离数组
// 小顶堆
priority_queue<PII, vector<PII>, greater<PII>> q;
int n; // n个城镇
int m; // m条路径
int S; // 起点
int T; // 终点
// 维护邻接表
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int dijkstra() {
memset(d, 0x3f, sizeof d); // 初始化为无穷大
d[S] = 0; // 出发点的距离初始化为0
q.push({0, S}); // 源点入队列
// q里装的 first:距离出发点的距离 second:结点编号
while (q.size()) {
PII t = q.top();
q.pop();
int u = t.second;
// 如果此结点已经被尝试过后,而且排在小顶堆的后面被尝试,说明不会更优秀
if (st[u]) continue;
// 用这个点去尝试更新相关的点
st[u] = true;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (d[v] > t.first + w[i]) {
d[v] = t.first + w[i];
q.push({d[v], v});
}
}
}
return d[T];
}
// 30 ms 还是推荐记忆这个,方便,代码短
int main() {
cin >> n >> m >> S >> T;
memset(h, -1, sizeof h);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
printf("%d\n", dijkstra());
return 0;
}