[AcWing 1129] 热浪


起点到终点的最短距离
堆优化 dijkstra
复杂度 \(O(m \cdot log(n)) = 6200 \times log(2500) \approx 7 \times 10^4\)
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const int N = 1e6 + 10;
int n, m, sp, ep;
int h[N], e[N], ne[N], w[N], idx;
int d[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
void dijkstra(int sp)
{
memset(d, 0x3f, sizeof d);
memset(st, false, sizeof st);
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, sp});
d[sp] = 0;
while (heap.size()) {
auto t = heap.top();
heap.pop();
auto v = t.second;
if (st[v])
continue;
st[v] = true;
for (int i = h[v]; i != -1; i = ne[i]) {
int j = e[i];
if (d[j] > d[v] + w[i]) {
d[j] = d[v] + w[i];
heap.push({d[j], j});
}
}
}
}
void solve()
{
cin >> n >> m >> sp >> ep;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
dijkstra(sp);
cout << d[ep] << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
solve();
return 0;
}
- 非负权图尽量不用 \(SPFA\),容易被卡,用堆优化 \(dijkstra\)
- 此题的堆优化 \(dijkstra\) 模板可求以 \(sp\) 作为起点,到其他所有点的最短路

浙公网安备 33010602011771号