标签:
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7921 | Accepted: 2896 |
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
刚开始我以为只是针对终点N找次它的次短路,就只申请一个dis2变量,然后更新dis[N]时顺便更新dis2就可以,但是《程序设计》这本书上讲得好,不光是只找终点N的次短路,而且是找所有节点的次短路,所以就有了dis2[maxn]。
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<cstdio> #include<vector> #include<queue> #include<functional> using namespace std; #define maxr 100001 #define maxn 5002 #define inf 100000000 int n, r; //intersections,roads struct edge{ int to, cost; edge(const int a, const int b) :to(a), cost(b){} }; vector<edge> g[maxn]; //邻接矩阵 typedef pair<int, int> p; priority_queue<p, vector<p>, greater<p>> que; //优先队列 dijkstra int dis[maxn], dis2[maxn]; void solve(){ //initialization fill(dis, dis + maxn, inf); fill(dis2, dis2 + maxn, inf); // cin >> n >> r; int a, b, c; while (r--){ scanf("%d %d %d", &a, &b, &c); g[a].push_back(edge(b, c)); //刚开始我只是申请的edge临时变量,到后面调用的时候就会出错,所以直接添加了构造函数 g[b].push_back(edge(a, c)); } //从 N=1 开始的最短路 dis[1] = 0; que.push(p(0, 1)); while (!que.empty()){ p pir = que.top(); que.pop(); int v = pir.second, d = pir.first; if (dis2[v] < d)continue; for (int i = 0; i < g[v].size(); i++){ edge &e = g[v][i]; int d2 = e.cost + d; if (dis[e.to]>d2){ swap(dis[e.to], d2); que.push(p(dis[e.to], e.to)); } if (dis2[e.to]>d2&&dis[e.to] < d2){ dis2[e.to] = d2; que.push(p(dis2[e.to], e.to)); } } } printf("%d\n", dis2[n]); } int main() { solve(); // getchar(); return 0; }
标签:
原文地址:http://www.cnblogs.com/littlehoom/p/4210244.html