1133. 第二短路

思路

dijkstra 求最短路的过程中维护次短路,需要注意 “严格” 的问题。

AC code

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
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

struct Node{
int v, type, dis;
bool operator > (const Node& node) const{
return dis > node.dis;
}
};

const int N = 5010, M = 200010;
int h[N], e[M], w[M], ne[M], idx;
int dist[N][2];
bool st[N][2];
int n, r;

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

int dijkstra(){
memset(dist, 0x3f, sizeof(dist));
memset(st, false, sizeof(st));
dist[1][0] = 0;

priority_queue<Node, vector<Node>, greater<Node>> q;
q.push({1, 0, 0});

while(q.size()){
auto p = q.top();
q.pop();
int v = p.v, type = p.type, dis = p.dis;
if(st[v][type]) continue;
st[v][type] = true;
for(int i = h[v]; ~i; i = ne[i]){
int j = e[i];
if(dist[j][0] > dis + w[i]){
dist[j][1] = dist[j][0];
q.push({j, 1, dist[j][1]});
dist[j][0] = dis + w[i];
q.push({j, 0, dist[j][0]});
}
else if(dist[j][1] > dis + w[i] && dist[j][0] < dis + w[i]){
dist[j][1] = dis + w[i];
q.push({j, 1, dist[j][1]});
}
}
}
return dist[n][1];
}

int main(){
cin >> n >> r;
memset(h, -1, sizeof(h));
for(int i = 0; i < r; i++){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
cout << dijkstra() << endl;
return 0;
}