挑战程序设计竞赛2.5例题:Roadblocks POJ - 3255 次短路问题
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
#include <stdio.h> #include <vector> #include <queue> #include <algorithm> using namespace std; const int INF = 0x3fffffff; struct Node{ int to; int value; Node(int x, int y){ to = x; value = y; } friend bool operator <(Node x, Node y){ return x.value > y.value; } }; priority_queue<Node> pq; int min_dis[5005], sec_dis[5005];//最短路,次短路 vector<Node> v[5005];//邻接表 int main(void) { int n, r; int from, to, cost; scanf("%d %d", &n, &r); for(int i = 0; i < r; i++) { scanf("%d %d %d", &from, &to, &cost); v[from].push_back(Node(to, cost)); v[to].push_back(Node(from, cost)); } fill(min_dis, min_dis + n + 1, INF); fill(sec_dis, sec_dis + n + 1, INF); min_dis[1] = 0; //第一个点到自己为0 pq.push(Node(1, 0)); while(!pq.empty()) { Node temp = pq.top(); pq.pop(); if(temp.value > sec_dis[temp.to])//如果大于次短路,那么没有必要更新 continue; for(int i = 0; i < v[temp.to].size(); i++) { int d = v[temp.to][i].value + temp.value; if(d < min_dis[v[temp.to][i].to]) { swap(min_dis[v[temp.to][i].to], d); pq.push(Node(v[temp.to][i].to, min_dis[v[temp.to][i].to])); } if(d > min_dis[v[temp.to][i].to] && d < sec_dis[v[temp.to][i].to]) { sec_dis[v[temp.to][i].to] = d; pq.push(Node(v[temp.to][i].to, sec_dis[v[temp.to][i].to])); } } } printf("%d\n", sec_dis[n]); return 0; }