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
|
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e6+10;
int h[N], ne[N], e[N], w[N], idx;
int n, m;
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(){
// 1. 初始化
memset(dis, 0x3f, sizeof(dis));
dis[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({dis[1], 1});
while(heap.size()){
// 2. 找到距离最短的点,并且标记
auto t = heap.top();
heap.pop();
int node = t.second, distance = t.first;
// 已经访问过,这个为冗余边
if(st[node]) continue;
st[node] = true;
// 3. 用当前点更新其他点的距离。
for(int i = h[node]; i != -1; i = ne[i]){
int j = e[i];
if(dis[j] > dis[node] + w[i]){
dis[j] = dis[node] + w[i];
heap.push({dis[j], j});
}
}
}
if(dis[n] == 0x3f3f3f3f) return -1;
else return dis[n];
}
int main(){
cin >> n >> m;
memset(h, -1, sizeof(h));
while(m-- ){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int t = dijkstra();
cout << t << endl;
return 0;
}
|