稀疏图,基于邻接表的优化版Dijkstra算法
    时间复杂度分析:外层循环由heap.size()决定,heap.size()的大小由heap.push决定,最多加m次边,故外层循环最多为m,内层循环是Acwing850. Dijkstra求最短路 II - 图1,同时要考虑到最初的加m条边,故总的时间复杂度为Acwing850. Dijkstra求最短路 II - 图2

    1. #include<iostream>
    2. #include<algorithm>
    3. #include<cstring>
    4. #include<queue>
    5. using namespace std;
    6. const int N = 1e6+10;
    7. typedef pair<int,int> PII;
    8. // 稀疏图用邻接表存储
    9. int h[N],w[N],e[N],ne[N],idx;
    10. int dist[N]; // 距离起点的距离
    11. bool st[N]; // 标记是否已更新为最短距离
    12. int n,m;
    13. // 加一条a指向b的边,权重为c
    14. void add(int a,int b,int c){
    15. e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
    16. }
    17. int dijkstra(){
    18. memset(dist,0x3f,sizeof dist);
    19. dist[1] = 0;
    20. priority_queue<PII,vector<PII>,greater<PII>> heap;
    21. heap.push({0,1}); // 第一关键字是距离,第二关键字是编号
    22. while(heap.size()){
    23. int distance = heap.top().first, id = heap.top().second;
    24. heap.pop();
    25. if(st[id]) continue; // 如果已经更新过了就跳过
    26. st[id] = true;
    27. for(int i = h[id];i!=-1;i=ne[i]){
    28. int j = e[i];
    29. if(dist[j]>dist[id]+w[i]){
    30. dist[j] = dist[id]+w[i]; // 更新距离
    31. heap.push({dist[j],j});
    32. }
    33. }
    34. }
    35. if(dist[n]==0x3f3f3f3f) return -1;
    36. else return dist[n];
    37. }
    38. int main(){
    39. cin >> n >>m;
    40. // 初始化链表头
    41. memset(h,-1,sizeof h);
    42. while(m--){
    43. int a,b,c;
    44. cin >> a >> b >> c;
    45. add(a,b,c);
    46. }
    47. cout << dijkstra() << endl;
    48. return 0;
    49. }