首页 > 代码库 > Roadblocks http://poj.org/problem?id=3255
Roadblocks http://poj.org/problem?id=3255
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 41 2 1002 4 2002 3 2503 4 100
Sample Output
450
Hint
1 #include"iostream" 2 #include"cstdio" 3 #include"cstring" 4 #include"algorithm" 5 #include"cstdlib" 6 #include"queue" 7 #include"vector" 8 using namespace std; 9 const int inf=0x7fffffff;10 const int ms=100001;11 struct edge12 {13 //int from;14 int to;15 int cost;16 };17 typedef pair<int,int> P;18 int main()19 {20 int i,j,N,R,ans,a,b,w;21 scanf("%d%d",&N,&R);22 vector<edge> vec[N+1]; 23 for(i=1;i<=R;i++)24 {25 scanf("%d%d%d",&a,&b,&w);26 edge e;27 e.to=b;28 e.cost=w;29 //vec[a].push_back(edge{b,w}); 有警告 30 vec[a].push_back(e);31 e.to=a;32 vec[b].push_back(e);33 }34 int dist[N+1],dist2[N+1];35 priority_queue<P,vector<P>,greater<P> > que;36 fill(dist,dist+N+1,inf);37 fill(dist2,dist2+N+1,inf);38 dist[1]=0;39 que.push(P(0,1));40 while(!que.empty())41 {42 P p=que.top();43 que.pop();44 int v=p.second;45 int d=p.first;46 if(dist2[v]<d)47 continue;48 for(i=0;i<vec[v].size();i++)49 {50 edge &e=vec[v][i];51 int d2=d+e.cost;52 if(dist[e.to]>d2)53 {54 swap(dist[e.to],d2);55 que.push(P(dist[e.to],e.to));56 }57 if(dist2[e.to]>d2&&dist[e.to]<d2)58 {59 dist2[e.to]=d2;60 que.push(P(dist2[e.to],e.to));61 }62 }63 }64 //printf("%d\n",dist2[N]);65 cout<<dist2[N]<<endl;66 return 0;67 }