次短路
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Line 1: Two space-separated integers: N and R
Lines 2.. R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4 1 2 100 2 4 200 2 3 250 3 4 100
Sample Output
450
Hint
Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
两次最短:
从起点跑一次最短路,然后再从终点跑一次最短路,然后遍历一遍所有的边,次短路的距离就是其中某条边的权值加上起点到一个点的最短路加上终点到另一个点的最短路
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int inf=0x3f3f3f3f; 5 const int maxn=1e6+10; 6 7 struct node{ 8 int v,w,next; 9 }e[maxn]; 10 int dis1[maxn]; 11 int dis2[maxn]; 12 int head[maxn]; 13 int vis[maxn]; 14 int num=0; 15 void init() 16 { 17 num=0; 18 memset(head,-1,sizeof(head)); 19 memset(e,0,sizeof(e)); 20 memset(dis1,inf,sizeof(dis1)); 21 memset(dis2,inf,sizeof(dis2)); 22 } 23 void add(int u,int v,int w) 24 { 25 e[num].v=v; 26 e[num].w=w; 27 e[num].next=head[u]; 28 head[u]=num++; 29 } 30 void spfa(int u,int *dis) 31 { 32 queue<int> q; 33 memset(vis,0,sizeof(vis)); 34 dis[u]=0; 35 vis[u]=1; 36 q.push(u); 37 while(!q.empty()) 38 { 39 u=q.front(); 40 q.pop(); 41 vis[u]=0; 42 for(int i=head[u];i!=-1;i=e[i].next) 43 { 44 int v=e[i].v; 45 int w=e[i].w; 46 if(dis[v]>dis[u]+w) 47 { 48 dis[v]=dis[u]+w; 49 if(!vis[v]) 50 { 51 vis[v]=1; 52 q.push(v); 53 } 54 } 55 } 56 } 57 } 58 int main() 59 { 60 int n,m,u,v,w; 61 cin>>n>>m; 62 init(); 63 for(int i=1;i<=m;i++) 64 { 65 cin>>u>>v>>w; 66 add(u,v,w); 67 add(v,u,w); 68 } 69 spfa(1,dis1); 70 spfa(n,dis2); 71 int ans=inf;//次短路 72 for(int i=1;i<=n;i++) 73 { 74 for(int j=head[i];j!=-1;j=e[j].next) 75 { 76 v=e[j].v; 77 w=e[j].w; 78 int tem=dis1[i]+dis2[v]+w;//1~n的路径 79 if(ans>tem)//更新次短路 80 { 81 if(tem>dis1[n])//tem>最短路 82 ans=tem; 83 } 84 } 85 } 86 cout<<ans<<endl; 87 }