Dijkstra次短路

本文介绍使用Dijkstra算法求解图中两点间次短路径的方法。通过引入两个变量分别记录最短和次短路径,并利用优先队列优化搜索过程。提供了一段C++实现代码作为示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dijkstra次短路

其实就是带入两个变量进行增广,一个表示最短,一个表示次短。
接下来讲一下如何用堆维护,每当更新到了最短或次短,就将这个答案put进堆里就可以了。堆的大小不是很清楚,建议用调优先队列。

例题

传送门

代码如下

#include<cstdio>
#include<cctype>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN=5005,MAXM=1e5+5;
int n,m,len,Ans=1e9,MAX=1e9,dst[2][MAXN];
struct Edge{
	int tot,lnk[MAXN],nxt[MAXM<<1],son[MAXM<<1],W[MAXM<<1];
	void Add(int x,int y,int w){nxt[++tot]=lnk[x];lnk[x]=tot;son[tot]=y,W[tot]=w;}
}E;
int read(){
	int ret=0;char ch=getchar();bool f=1;
	for(;!isdigit(ch);ch=getchar()) f^=!(ch^'-');
	for(; isdigit(ch);ch=getchar()) ret=(ret<<1)+(ret<<3)+ch-48;
	return f?ret:-ret;
}
struct xcw{
	int x,id;
	bool operator <(const xcw b)const{return x>b.x;}
}hep[MAXM];
void put(int x,int id){hep[++len]=(xcw){x,id};push_heap(hep+1,hep+1+len);}
xcw get(){pop_heap(hep+1,hep+1+len);return hep[len--];}
void DIJ(){
	memset(dst,63,sizeof(dst));put(0,1);dst[0][1]=0;
	while(len){
		xcw OUT=get();
		int k=OUT.id,MIN=OUT.x;
		if(dst[1][k]<MIN) continue;
		for(int j=E.lnk[k];j;j=E.nxt[j]){
			int Now=MIN+E.W[j];
			if(dst[0][E.son[j]]>Now) swap(dst[0][E.son[j]],Now),put(dst[0][E.son[j]],E.son[j]);
			if(dst[1][E.son[j]]>Now&&Now>dst[0][E.son[j]]) swap(dst[1][E.son[j]],Now),put(dst[1][E.son[j]],E.son[j]);
		}
	}
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("prob.in","r",stdin);
	freopen("prob.out","w",stdout);
	#endif
	n=read(),m=read();
	for(int i=1,x,y,w;i<=m;i++) x=read(),y=read(),w=read(),E.Add(x,y,w),E.Add(y,x,w);
	DIJ();
	printf("%d\n",dst[1][n]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值