标签:
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
Output
Sample Input
4 4 1 2 100 2 4 200 2 3 250 3 4 100
Sample Output
450
Hint
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 #include <vector> 7 #include <queue> 8 9 #define MAX_V 5002 10 #define inf 999999 11 using namespace std; 12 13 struct edge 14 { 15 int to; 16 int cost; 17 }; 18 19 typedef pair<int , int> P; 20 int V; 21 vector<edge> G[MAX_V]; 22 23 int n, r; 24 int dist[MAX_V]; 25 int dist2[MAX_V]; 26 27 priority_queue<P, vector<P>, greater<P> > que; 28 29 int main(int argc, char const *argv[]) 30 { 31 //freopen("input.txt","r",stdin); 32 while(scanf("%d %d",&n,&r) != EOF) { 33 while(r--) { 34 int a, b ,dis; 35 scanf("%d %d %d",&a,&b,&dis); 36 edge p, q; 37 p.to = b-1; 38 p.cost = dis; 39 G[a-1].push_back(p); 40 q.to = a - 1; 41 q.cost = dis; 42 G[b-1].push_back(q); 43 } 44 fill(dist, dist+n, inf); 45 fill(dist2, dist2+n, inf); 46 dist[0] = 0; 47 que.push(P(0,0)); 48 while(!que.empty()) { 49 P p = que.top(); 50 que.pop(); 51 int v = p.second, d = p.first; 52 if(dist2[v] < d) { 53 continue; 54 } 55 for(int i = 0; i < G[v].size(); i++) { 56 edge &e = G[v][i]; 57 int d2 = d + e.cost; 58 if(dist[e.to] > d2) { 59 swap(dist[e.to], d2); 60 que.push(P(dist[e.to], e.to)); 61 } 62 if(dist2[e.to] > d2 && dist[e.to] < d2) { 63 dist2[e.to] = d2; 64 que.push(P(dist2[e.to], e.to)); 65 } 66 } 67 } 68 printf("%d\n",dist2[n-1]); 69 } 70 return 0; 71 }
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5794349.html