dijstra求第二短路径

#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;
}
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值