Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 10640 | Accepted: 3775 |
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
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int maxn = 100000; const int inf = 0x3f3f3f3f; struct Edge { int key; int next; int c; }edge[maxn<<1]; int pre[5010],df[5010],ds[5010]; int n,r,cnt; bool vis[5010]; void addedge(int x,int y,int w) { edge[cnt].key = y; edge[cnt].c = w; edge[cnt].next = pre[x]; pre[x] = cnt++; } void SPFA(int src,int *d) { queue<int> que; memset(vis,false,sizeof(vis)); vis[src] = true; d[src] = 0; que.push(src); while(!que.empty()) { int v = que.front(); que.pop(); vis[v] = false; for(int i = pre[v]; i != -1; i = edge[i].next) { int k = edge[i].key; if(d[k] > d[v] + edge[i].c) { d[k] = d[v] + edge[i].c; if(vis[k] == false) { vis[k] = true; que.push(k); } } } } } void init() { memset(pre,-1,sizeof(pre)); memset(df,inf,sizeof(df)); memset(ds,inf,sizeof(ds)); cnt = 0; } int main() { while(scanf("%d%d",&n,&r)!=EOF) { init(); for(int i = 1; i <= r; i++) { int a,b,d; scanf("%d%d%d",&a,&b,&d); addedge(a,b,d); addedge(b,a,d); } SPFA(1,df); SPFA(n,ds); int ans = inf; for(int i = 1; i <= n; i++) { for(int j = pre[i]; j != -1; j = edge[j].next) { int k = edge[j].key; if(df[i] + ds[k] + edge[j].c > df[n] && df[i] + ds[k] + edge[j].c < ans) ans = df[i] + ds[k] + edge[j].c; } } printf("%d\n",ans); } return 0; }