「POJ3255」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
1 2 3 4 5 |
4 4 1 2 100 2 4 200 2 3 250 3 4 100 |
Sample Output
1 |
450 |
Hint
题解
同匈牙利游戏
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 53 54 55 56 57 58 59 60 61 62 63 |
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int cnt,n,m,q[5001],head[5001]; bool inq[5001]; long long dis[5001],dis2[5001]; struct data{int to,next,v;}e[200001]; void insert(int u,int v,int w) { cnt++; e[cnt].to=v; e[cnt].v=w; e[cnt].next=head[u]; head[u]=cnt; } void spfa() { int t=0,w=1,now,i; q[0]=1;inq[1]=1;dis[1]=0; while(t!=w) { now=q[t];t++;if(t==n)t=0; i=head[now]; while(i) { if(dis[now]+e[i].v<dis[e[i].to]) { dis2[e[i].to]=dis[e[i].to]; dis[e[i].to]=dis[now]+e[i].v; if(!inq[e[i].to]){inq[e[i].to]=1;q[w]=e[i].to;w++;if(w==n)w=0;} } else if(dis[now]+e[i].v<dis2[e[i].to]&&dis[now]+e[i].v>dis[e[i].to]) { dis2[e[i].to]=dis[now]+e[i].v; if(!inq[e[i].to]){inq[e[i].to]=1;q[w]=e[i].to;w++;if(w==n)w=0;} } if(dis2[now]+e[i].v<dis2[e[i].to]) { dis2[e[i].to]=dis2[now]+e[i].v; if(!inq[e[i].to]){inq[e[i].to]=1;q[w]=e[i].to;w++;if(w==n)w=0;} } i=e[i].next; } inq[now]=0; } if(dis2[n]!=1e15)printf("%d",dis2[n]); else printf("-1"); } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)dis[i]=dis2[i]=1e15; for(int i=1;i<=m;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); insert(u,v,w); insert(v,u,w); } spfa(); return 0; } |