D.Roadblocks(次短路)

12 篇文章 0 订阅

https://ac.nowcoder.com/acm/contest/945/D

#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f3f
//#define LL long long
using namespace std;
const int maxn=1000005;
int head[maxn];
int n,m,cnt;
int dis[maxn][2];
void init()
{
	cnt=0; 
	memset(head,-1,sizeof(head));
}
struct node
{
	int u,v,w,next;
}edge[maxn];
struct kt
{
	int to,w;
	kt(int a,int b)
	{
		to=a;w=b;
	}
	friend bool operator <(kt a,kt b)
	{
		return a.w>b.w;
	}
};
void addedge(int u,int v,int w)
{
	edge[cnt].u=u;
	edge[cnt].v=v;
	edge[cnt].w=w;
	edge[cnt].next=head[u];
	head[u]=cnt++;	
}
void djkstra()
{
	priority_queue<kt>q;
	memset(dis,0x3f,sizeof(dis));
	dis[1][0]=0;
	q.push(kt(1,0));
	while(!q.empty())
	{
		kt h=q.top();
		q.pop();
		int e=h.to;
		int hw=h.w;
		if(dis[e][1]<hw)
			continue;
		for(int i=head[e];i!=-1;i=edge[i].next)
		{
			int to=edge[i].v;
			int w=edge[i].w;
			if(dis[to][0]>hw+w)
			{
				dis[to][1]=dis[to][0];
				dis[to][0]=hw+w;
				q.push(kt(to,dis[to][0]));
				q.push(kt(to,dis[to][1]));
			}
			else if(hw+w>dis[to][0]&&hw+w<dis[to][1])
			{
				dis[to][1]=hw+w;
				q.push(kt(to,dis[to][1]));
			}
		}
	}
}
int main()
{
	cin>>n>>m;
	init();
	for(int i=0;i<m;i++)
	{
		int a,b,c;
		cin>>a>>b>>c;
		addedge(a,b,c);
		addedge(b,a,c);
	}
	djkstra();
	cout << dis[n][1] << endl;

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值