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题目大意:求无向图的·次短路。
解题思路:到某个顶点v的次短路要么是到其他某个顶点u的最短路再加上u -> v的距离,要么是到u的次短路再加上u -> v的距离,因此所要求的就是到所有顶点的最短路和次短路。因此,对于每一个顶点,我们不仅记录最短距离,也将次短距离记录下来,然后利用Dijkstra算法不断更新这两个距离即可。
代码如下:
#include <cstdio>
#include <cstring>
#include <climits>
#include <queue>
#define INF INT_MAX / 10
using namespace std;
typedef pair<int,int> P;
const int maxn = 5005;//路口数
const int maxr = 200005;//道路数量
int first[maxn],dis1[maxn],dis2[maxn],e;
int next[maxr],v[maxr],w[maxr];
int n,r;
void init()
{
memset(first,-1,sizeof(first));
e = 1;
}
void add_edge(int from,int to,int dis)
{
v[e] = to;
next[e] = first[from];
w[e] = dis;
first[from] = e++;
}
priority_queue<P,vector<P>,greater<P> > que;
void dijkstra(int s)
{
while(que.size())
que.pop();
for(int i = 0;i <= n;i++){
dis1[i] = INF;
dis2[i] = INF;
}
dis1[s] = 0;
que.push(P(0,s));
while(que.size()){
P p = que.top();
que.pop();
int u = p.second;
int d1 = p.first;
if(dis2[u] < d1)
continue;
for(int i = first[u];i != -1;i = next[i]){
int d2 = d1 + w[i];
if(dis1[v[i]] > d2){
swap(dis1[v[i]],d2);
que.push(P(dis1[v[i]],v[i]));
}
if(dis2[v[i]] > d2 && dis1[v[i]] < d2){
dis2[v[i]] = d2;
que.push(P(dis2[v[i]],v[i]));
}
}
}
}
int main()
{
while(scanf("%d %d",&n,&r) != EOF){
int a,b,c;
init();
while(r--){
scanf("%d %d %d",&a,&b,&c);
add_edge(a,b,c);
add_edge(b,a,c);
}
dijkstra(1);
printf("%d\n",dis2[n]);
}
return 0;
}