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.

67 lines
1.9 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
/*
(spfa) O(m)
O(m)O(nm) O(n*m)
*/
const int N = 2510; // 端点数量
const int M = 6200 * 2 + 10; // 边的数量记得别开太小和N一样就等着挂吧
int n; // n个城镇
int m; // m条路径
int S; // 起点
int T; // 终点
int h[N], e[M], w[M], ne[M], idx; // 邻接表
int d[N]; // 最短距离数组
queue<int> q; // 队列
bool st[N]; // 是否使用过
// 邻接表模板
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
// spfa模板
void spfa() {
// 将所有距离初始化为无穷大
memset(d, 0x3f, sizeof d);
// 出发点的距离清零
d[S] = 0;
q.push(S); // 出发点入队列
st[S] = true; // 出发点标识已使用
while (q.size()) {
int u = q.front();
q.pop();
st[u] = false;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (d[v] > d[u] + w[i]) {
d[v] = d[u] + w[i];
if (!st[v]) {
st[v] = true;
q.push(v);
}
}
}
}
}
int main() {
// 输入n个城镇m条路径,S:起点T:终点
cin >> n >> m >> S >> T;
// 初始化邻接表
memset(h, -1, sizeof h);
// 读入m条路径
for (int i = 0; i < m; i++) {
// 每条路径的起点,终点,花费
int a, b, c;
cin >> a >> b >> c;
// 无向边
add(a, b, c), add(b, a, c);
}
spfa();
// 输出终点T的单源最短距离
printf("%d\n", d[T]);
return 0;
}