#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 1e5+5;
const long long minn = 3e9+5;
int head[maxn],cnt=0;
long long dis_1[maxn],dis_2[maxn];
struct node
{
int r;
long long w;
int next;
}edge[4*maxn];
struct tree
{
int pos;
long long dis;
};
void adde(int l,int r,long long w)
{
edge[cnt].r=r;
edge[cnt].w=w;
edge[cnt].next=head[l];
head[l]=cnt;
cnt++;
}
bool operator<(const tree &x,const tree &y)
{
return x.dis>y.dis;
}
void dij(int s,int t)
{
struct tree th,ch;
th.pos=s;
th.dis=0;
dis_1[s]=0;
priority_queue<tree> que;
que.push(th);
while(!que.empty())
{
ch=que.top();
que.pop();
if(dis_2[ch.pos]<ch.dis)
continue;
for(int i=head[ch.pos];i!=-1;i=edge[i].next)
{
int r=edge[i].r;
long long w=edge[i].w,d;
d=ch.dis+w;
if(dis_1[r]>d)
{
swap(dis_1[r],d);
th.dis=dis_1[r];
th.pos=r;
que.push(th);
}
if(dis_2[r]>d&&dis_1[r]<d) //严格第二最短路径
{
dis_2[r]=d;
th.dis=dis_2[r];
th.pos=r;
que.push(th);
}
}
}
}
int main()
{
int n,m,x,y;
long long w;
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<=n;i++)
{
head[i]=-1;
dis_1[i]=minn;
dis_2[i]=minn;
}
while(m--)
{
scanf("%d%d%lld",&x,&y,&w);
adde(x,y,w);
adde(y,x,w);
}
dij(1,n);
printf("%lld\n",dis_2[n]);
}
return 0;
}
dijstra求第二短路径
最新推荐文章于 2022-04-04 16:10:36 发布