Description
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
Sample Input
4 4 1 2 100 2 4 200 2 3 250 3 4 100
Sample Output
450
Hint
/* 引用: 求次短路,可以通过求最短路得到次短路长度 1到n的次短路长度必然产生于:从1走到x的最短路+edge[x][y]+y到n的最短路 首先预处理好1到每一个节点的最短路,和n到每一个节点的最短路 然后枚举每一条边作为中间边(x,y)或者(y,x),如果加起来长度等于最短路长度则跳过,否则更新 注意对每条边都要进行正向和反向的判断 */ #include <iostream> #include<queue> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int inf=0x7fffffff; int ans,minlen,n,m,t; int dis[5005],r_dis[5005],x[200003],y[200003],z[200003]; bool vis[5005]; struct node { int num,len; node(int a,int b){num=a; len=b;} }; vector<node> s[5005]; void spfa(int dis[],int k) { queue<int>Q; memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) dis[i]=inf; vis[k]=1; dis[k]=0; Q.push(k); while(!Q.empty()) { int u=Q.front(); Q.pop(); vis[u]=0; for(int i=0;i<s[u].size();i++) { if (dis[s[u][i].num]<=dis[u]+s[u][i].len) continue; dis[s[u][i].num]=dis[u]+s[u][i].len; if(!vis[s[u][i].num]) { vis[s[u][i].num]=1; Q.push(s[u][i].num); } } } } int main() { while(~scanf("%d%d",&n,&m)) { for(int i=1;i<=n;i++) s[i].clear(); for(int i=1;i<=m;i++) { scanf("%d%d%d",&x[i],&y[i],&z[i]); s[x[i]].push_back(node(y[i],z[i])); s[y[i]].push_back(node(x[i],z[i])); x[i+m]=y[i]; y[i+m]=x[i]; z[i+m]=z[i]; } spfa(dis,1); spfa(r_dis,n); ans=inf; /*for(int i=1;i<=n;i++) printf("%d ",dis[i]); printf(" "); for(int i=1;i<=n;i++) printf("%d ",r_dis[i]); printf(" ");*/ for(int i=1;i<=2*m;i++) { if (dis[x[i]]+r_dis[y[i]]+z[i]>dis[n]) ans=min(ans,dis[x[i]]+r_dis[y[i]]+z[i]); } printf("%d ",ans); } return 0; }