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
题目大意:
给定一个无向图,求从1号点到n号点的所有路径长度中第二长的。
核心思想:
次短路模板题。
代码如下:
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cmath>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int N=5e3+20,M=2e5+20;
int head[N],cnt,dis[N],td[N];
bool vis[N];
//用于邻接表
struct node
{
int y,v,ne;
} side[M];
//用于优先队列
struct Node
{
int y,v;
Node()
{
}
Node(int yy,int vv)
{
y=yy;
v=vv;
}
bool operator<(const Node oth)const
{
return v>oth.v;
}
};
//邻接表添加边
void add(int x,int y,int v)
{
side[cnt].y=y;
side[cnt].v=v;
side[cnt].ne=head[x];
head[x]=cnt++;
return;
}
void dij(int st)
{
for(int i=0; i<N; i++)
{
dis[i]=inf;
vis[i]=0;
}
dis[st]=0;
priority_queue<Node>q;//优先队列优化
q.push(Node(st,0));
while(!q.empty())
{
int te=q.top().y;
q.pop();
if(vis[te])continue;
vis[te]=1;
for(int i=head[te]; i!=-1; i=side[i].ne)
{
int ty=side[i].y;
int tv=side[i].v;
if(dis[ty]>dis[te]+tv)
{
dis[ty]=dis[te]+tv;
q.push(Node(ty,dis[ty]));
}
}
}
return;
}
void init()
{
for(int i=0; i<N; i++)
head[i]=-1;
cnt=0;
return;
}
int main()
{
int n,m,x,y,v;
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=0; i<m; i++)
{
scanf("%d%d%d",&x,&y,&v);
add(x,y,v);
add(y,x,v);
}
//正向跑Dijkstra
dij(1);
for(int i=1;i<=n;i++)
td[i]=dis[i];
//反向跑Dijkstra
dij(n);
//枚举边,取次优值
int ans=inf;
for(int i=0;i<cnt;i++)
{
x=side[i^1].y;
y=side[i].y;
int t=dis[x]+td[y]+side[i].v;
if(t>dis[1])
ans=min(ans,t);
}
printf("%d\n",ans);
}
return 0;
}