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
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
4 4 1 2 100 2 4 200 2 3 250 3 4 100Sample Output
450Hint
#include<iostream> #include<cstring> #include<stdlib.h> #include<stdio.h> #include<algorithm> #include<queue> #define MAXN 300000 using namespace std; struct edge{ int first; int next; int quan; int to; }a[MAXN*2]; queue<int> q; int dis[MAXN],dis2[MAXN],have[MAXN]; int n,m,num=0; void addedge(int from,int to,int quan){ a[++num].to=to; a[num].quan=quan; a[num].next=a[from].first; a[from].first=num; } void spfa(){ memset(have,0,sizeof(have)); memset(dis,127,sizeof(dis)); memset(dis2,127,sizeof(dis2)); while(!q.empty()) q.pop(); q.push(1); dis[1]=0; while(!q.empty()){ int now=q.front(); q.pop(); have[now]=0; for(int i=a[now].first;i;i=a[i].next){ int to=a[i].to,quan=a[i].quan; int diss=dis[now]+quan,diss2=dis2[now]+quan; if(dis[to]>diss){ swap(dis[to],diss); if(!have[to]) {have[to]=1,q.push(to);} } if(dis2[to]>diss&&dis[to]<diss){ dis2[to]=diss; if(!have[to]) {have[to]=1,q.push(to);} } if(dis2[to]>diss2&&dis[to]<diss2){ dis2[to]=diss2; if(!have[to]) {have[to]=1;q.push(to);} } } } } int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ int x,y,z; scanf("%d%d%d",&x,&y,&z); addedge(x,y,z),addedge(y,x,z); } spfa(); printf("%d",dis2[n]); }