题目链接:POJ 3255
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
Line 1: Two space-separated integers: N and R
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
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
Hint
Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
题意
某街道共有R条道路,N个路口。道路双向通道。问1号路口到N号路口的次短路长度是多少?同一条边可以经过多次。
思路
到某一顶点v的次短路要么是到其他某个顶点u的最短路再加上u->v的边,要么是到u的次最短路再加上u->v的边,所以需要维护两个数字,最短路数组(dis1[maxn])和次短路数组(dis2[maxn]);
小技巧:
为了节省时间,使用的堆优化,其中typedef pair<int,int> P;first为最短路,second为顶点编号
AC代码
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<utility>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> P; //first为最短路,second为顶点编号
const int maxn = 5010;
const int inf = 0x3f3f3f3f;
const double dnf = 1.0e5;
struct edge{
int to,cost;
};
vector<edge> Adj[maxn]; //链表构图
int n,m;
int dis1[maxn],dis2[maxn]; //最短路,次短路数组
void Init()
{
for(int i=1;i<=n;i++)
Adj[i].clear();
}
void add(int u,int v,int c)
{
edge tmp;
tmp.to = v;
tmp.cost = c;
Adj[u].push_back(tmp);
}
void Dijkstra()
{
priority_queue<P,vector<P>,greater<P> > q;
for(int i=1;i<=n;i++){
dis1[i] = dis2[i] = inf;
}
dis1[1] = 0;
q.push(P(0,1));
while(!q.empty()){
P p = q.top();
q.pop();
int u = p.second;
int d = p.first;
if(dis2[u]<d) continue;
for(int i=0;i<Adj[u].size();i++){
int v = Adj[u][i].to;
int d2 = d + Adj[u][i].cost;
if(dis1[v]>d2){ //先更新最短路
swap(dis1[v],d2); //因为还要更新次短路,所以不能覆盖原来的dis1[v]
q.push(P(dis1[v],v)); //入队
}
if(dis2[v]>d2&&dis1[v]<d2){ //更新次短路
dis2[v] = d2;
q.push(P(dis2[v],v)); //入队
}
}
}
printf("%d\n",dis2[n]); //输出
}
int main(void)
{
int u,v,c;
scanf("%d%d",&n,&m);
Init();
for(int i=1;i<=m;i++){
scanf("%d%d%d",&u,&v,&c);
add(u,v,c);
add(v,u,c);
}
Dijkstra();
return 0;
}