POJ --- 3255 Roadblocks
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 6459 | Accepted: 2406 |
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
思路:求次短路,先spfa,再枚举各条边,次短路一定是最短路换一条边得到。
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #define MAX 100005 6 #define INF 0xfffffff 7 using namespace std; 8 typedef struct{ 9 int from, to, next, w; 10 }Node; 11 Node edge[2*MAX]; 12 queue<int>q; 13 int head[MAX], vis[MAX], dist[MAX], rdist[MAX]; 14 void init(int n){ 15 memset(head, -1, sizeof(head)); 16 for(int i = 1;i <= n;i ++) 17 dist[i] = rdist[i] = INF; 18 dist[1] = rdist[n] = 0; 19 } 20 void spfa(int s, int dist[]){ 21 while(!q.empty()) q.pop(); 22 memset(vis, 0, sizeof(vis)); 23 q.push(s); 24 vis[s] = 1; 25 while(!q.empty()){ 26 int p = q.front(); 27 q.pop(); 28 vis[p] = 0; 29 for(int i = head[p];i != -1;i = edge[i].next){ 30 int v = edge[i].to; 31 if(dist[v] > dist[p] + edge[i].w){ 32 dist[v] = dist[p] + edge[i].w; 33 if(!vis[v]){ 34 q.push(v); 35 vis[v] = 1; 36 } 37 } 38 } 39 } 40 } 41 void AddEdge(int u, int v, int w, int i){ 42 edge[i].from = u; 43 edge[i].to = v; 44 edge[i].w = w; 45 edge[i].next = head[u]; 46 head[u] = i; 47 } 48 int main(){ 49 int R, N, u, v, w, secl; 50 //freopen("in.c", "r", stdin); 51 while(~scanf("%d%d", &N, &R)){ 52 init(N); 53 int i = 0; 54 for(int j = 0;j < R;j ++){ 55 scanf("%d%d%d", &u, &v, &w); 56 AddEdge(u, v, w, ++i); 57 AddEdge(v, u, w, ++i); 58 } 59 spfa(1, dist); 60 spfa(N, rdist); 61 secl = INF; 62 for(int j = 1;j <= i;j ++){ 63 u = edge[j].from; 64 v = edge[j].to; 65 if(dist[u] + edge[j].w + rdist[v] > dist[N] && secl > dist[u] + edge[j].w + rdist[v]) 66 secl = dist[u] + edge[j].w + rdist[v]; 67 } 68 printf("%d\n", secl); 69 } 70 return 0; 71 }