dijkstra求次短路

  1. dist[ i ][ 0 ]表示到点 i 的最短路 , dist[ i ][ 1 ]表示到点 i 的次短路

  2. 最短路何时更新:当dist[ i ][ 0 ] > len(j) + val( j , i )时,直接更新最短路
    次短路何时更新:当dist[ i ][ 0 ] < len(j) + val( j , i ) < dist[ i ][ 1 ]时,更新次短路

模板

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
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
typedef pair<int,int>P;
const int maxn = 100000 + 7;
struct Edge{
int to,next,val;
}edge[maxn];
int n,m,head[maxn],dist[maxn][2],tot;
void addEdge(int a,int b,int c){
edge[tot].to = b;edge[tot].val = c;edge[tot].next = head[a];head[a] = tot++;
}
void Dijkstra(int s){
for(int i = 0;i<=n;i++)dist[i][0] = dist[i][1] = INF;
dist[s][0] = 0;
priority_queue<P,vector<P>, greater<P> >que;
que.push(P(0,s));
while(!que.empty()){
P p = que.top();
que.pop();
if(p.first > dist[p.second][1])continue;
for(int i = head[p.second];~i;i = edge[i].next){
int d = p.first + edge[i].val;
if(dist[edge[i].to][0] > d){//更新最短路
swap(dist[edge[i].to][0] , d);//交换!!!
que.push(P(d,edge[i].to));
}
if(dist[edge[i].to][1] > d&&dist[edge[i].to][0] < d){//更新次短路
dist[edge[i].to][1] = d;
que.push(P(d,edge[i].to));
}
}
}
}
int main()
{
tot = 0;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i = 0;i<m;i++){
int a,b,v;
scanf("%d%d%d",&a,&b,&v);
addEdge(a,b,v);
addEdge(b,a,v);
}
int s,t;
scanf("%d%d",&s,&t);
Dijkstra(s);
printf("%d %d\n",dist[t][0],dist[t][1]);
return 0;
}