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).
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)
4 4 1 2 100 2 4 200 2 3 250 3 4 100Sample Output
450
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<algorithm>
#define bug(x) printf("%d***\n",x)
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxm= 100010;
const int maxn=5010;
int n,m;
int cnt;
int head[maxm*2];
struct Edge{
int v,nt;
int w;
}edge[maxm*2];
void add_edge(int u,int v,int w){
edge[cnt].nt=head[u];
edge[cnt].v=v;
edge[cnt].w=w;
head[u]=cnt++;
}
struct EEdge{
int o,w;
bool operator<(const EEdge& b)const{
return w>b.w;//?????
}
};
priority_queue<EEdge> pq;
/*
//同时更新最短路和次短路,只初始化最短路
不用vis,数组,如果我们用了vis的话,我们的次短路就没有办法更新了
*/
int dis1[maxn],dis2[maxn];
int dijstra(){
memset(dis1,inf,sizeof(dis1));
memset(dis2,inf,sizeof(dis2));
dis1[1]=0;
EEdge now,nxt;
now.o=1,now.w=0;
pq.push(now);
while(pq.size()){
now=pq.top();
pq.pop();
int no=now.o,nd=now.w;//拿来我们准备松弛的点
if(dis2[no]<nd) continue;//当前点如果大于次短路的话,就没有必要再去判断了
for(int i=head[no];i!=-1;i=edge[i].nt){
int v=edge[i].v,w=edge[i].w;
int sd=nd+w;//可以松弛的最短距离
if(sd<dis1[v]){ //如果可以更新最短距离,更新
swap(dis1[v],sd);
nxt.o=v,nxt.w=dis1[v];
pq.push(nxt);
}
if(sd<dis2[v]&&sd>dis1[v]){//如果当前点小于次短路,大于最短路的话,我们也去更新
dis2[v]=sd;
nxt.o=v,nxt.w=dis2[v];
pq.push(nxt);
}
}
}
return dis2[n];
}
int main(){
cnt=0;
scanf("%d %d",&n,&m);
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++){
int a,b,w;
scanf("%d %d %d",&a,&b,&w);
add_edge(a,b,w);
add_edge(b,a,w);
}
int ans=dijstra();
printf("%d\n",ans);
return 0;
}