AcWing 850. Dijkstra求最短路 II(堆优化版,适用于稀疏图)
AcWing 850. Dijkstra求最短路 II

使用堆找到不在s中,距离最近的点,降低时间复杂度,时间复杂度为mlogn
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
//堆里存一对编号,先存最小值,再存结点
const int N = 150010;
int n, m;
//稀疏图用邻接表
int h[N], e[N], ne[N], w[N], idx;
int dis[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++;
}
int dijkstra(){
memset(dis, 0x3f, sizeof dis);
dis[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size()){
auto t = heap.top(); heap.pop();
int index = t.y, distance = t.x;
if(st[index]) continue;
st[index] = true;
for(int i = h[index]; i != -1; i = ne[i]){
int j = e[i];
if(dis[j] > distance + w[i]){
dis[j] = distance + w[i];
heap.push({dis[j], j});
}
}
}
//不连通
if(dis[n] == 0x3f3f3f3f) return -1;
return dis[n];
}
int main(){
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while(m--){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}

浙公网安备 33010602011771号