Roadblocks
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
分析:
//It is made by HolseLee on 17th Aug 2018 //POJ3255 #include<cstring> #include<cstdio> #include<cstdlib> #include<cmath> #include<iostream> #include<iomanip> #include<queue> #include<algorithm> #define Max(a,b) (a)>(b)?(a):(b) #define Min(a,b) (a)<(b)?(a):(b) #define Swap(a,b) (a)^=(b)^=(a)^=(b) using namespace std; const int N=5005; const int M=1e5+7; typedef pair<int,int> P; int n,m,head[N],siz,dis[N],dist[N]; struct Node{ int to,val,nxt; }edge[M<<1]; priority_queue<P,vector<P>,greater<P> > T; inline int read() { char ch=getchar();int num=0;bool flag=false; while(ch<'0'||ch>'9'){if(ch=='-')flag=true;ch=getchar();} while(ch>='0'&&ch<='9'){num=num*10+ch-'0';ch=getchar();} return flag?-num:num; } inline void add(int x,int y,int z) { edge[++siz].to=y; edge[siz].val=z; edge[siz].nxt=head[x]; head[x]=siz; } void dijkstra() { memset(dis,0x7f,sizeof(dis)); memset(dist,0x7f,sizeof(dist)); dis[1]=0; T.push(P(1,0)); int x,y,d,dt; while(!T.empty()){ x=T.top().first,d=T.top().second;T.pop(); if(dist[x]<d)continue; for(int i=head[x];i!=-1;i=edge[i].nxt){ y=edge[i].to; dt=d+edge[i].val; if(dis[y]>dt){ Swap(dis[y],dt); T.push(P(y,dis[y])); } if(dist[y]>dt&&dis[y]<dt){ dist[y]=dt; T.push(P(y,dist[y])); } } } } int main() { n=read();m=read(); int x,y,z; memset(head,-1,sizeof(head)); for(int i=1;i<=m;++i){ x=read(),y=read(),z=read(); add(x,y,z);add(y,x,z); } dijkstra(); printf("%d ",dist[n]); return 0; }