搜索与图论 - 堆优化版Dijkstra算法

算法的时间复杂度是$O(nlogm)$

算法的基本思路的基本思路与朴树版本的Dijkstra的差别在于:

每次寻找通过遍历的方式寻找最小值$O(n)$。变为使用堆进行优化$O(log n)$

基本思路:

  • 首先初始化所有点为正无穷,初始起点为0
  • 进行n - 1次循环
  • 每次利用堆找到最小值
  • 然后利用最小值,更新剩余点到起点的距离
  • 如果终点距离为正无穷,那么说明没有最短路

AcWing: 850. Dijkstra求最短路 II

来源: https://www.acwing.com/problem/content/852/

给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为非负值。

请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。

输入格式
第一行包含整数n和m。

接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。

输出格式
输出一个整数,表示1号点到n号点的最短距离。

如果路径不存在,则输出-1。

数据范围
$1≤n,m≤1.5×10^5,$
图中涉及边长均不小于0,且不超过10000。

输入样例:

1
2
3
4
3 3
1 2 2
2 3 1
1 3 4

输出样例:

1
3

C++实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
const int N = 200010, INF = 0x3f3f3f3f;
typedef pair<int, int> PII;
// 稠密图,所以使用邻接表来存储
int h[N], e[N], ne[N], w[N], idx;
int n, m;
int dist[N];
bool st[N];

int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
// 以fist 作为排序,生成一个最小堆
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size())
{
auto t = heap.top();
heap.pop();

int ver = t.second, k = t.first;
// 如果遍历过该点,跳过该点继续遍历
if (st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > k + w[i])
{
dist[j] = k + w[i];
heap.push({dist[j], j});
}
}
}
if (dist[n] == INF) return -1;
return dist[n];
}

void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
while(m--)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}

cout << dijkstra() << endl;
return 0;
}