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
64
65
66
67
68
69
70
71
72
|
#include <cstring>
#include <iostream>
#include <queue>
#include <utility>
typedef std::pair<int, int> PII; // <最短距离, 点编号>
const int N = 1000010;
const int INF = 0x3f3f3f3f;
int h[N], e[N], w[N], ne[N], idx; // 邻接表
int dist[N]; // 存储最短距离
bool st[N]; // 标记是否已经确定最短距离
int n, m;
// 添加一条边 a -> b,权值为 c
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
// 堆优化 Dijkstra 主函数
int dijkstra() {
std::memset(dist, INF, sizeof(dist));
dist[1] = 0;
std::priority_queue<PII, std::vector<PII>, std::greater<PII>> heap;
heap.push({0, 1}); // 起点入堆
while (heap.size())
{
PII t = heap.top();
heap.pop();
int ver = t.second;
if (st[ver]) continue; // 如果已经处理过,跳过
st[ver] = true;
// 遍历 ver 的所有出边
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[ver] + w[i])
{
dist[j] = dist[ver] + w[i];
heap.push({dist[j], j});
}
}
}
return dist[n] == INF ? -1 : dist[n];
}
int main()
{
std::memset(h, -1, sizeof(h)); // 初始化邻接表
std::cin >> n >> m;
for (int i = 0; i < m; ++ i)
{
int x, y, z;
std::cin >> x >> y >> z;
add(x, y, z); // 构建图
}
std::cout << dijkstra() << '\n';
return 0;
}
|