Files
python/TangDou/AcWing_TiGao/T3/MiniPath/1129_SPFA.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

67 lines
1.9 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;
/*
(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;
}