P2865 [USACO06NOV] Roadblocks G

*原题链接*

次短路模版题

在刚学最短路时,我做过这道题集合位置,那时博客上写的是枚举删除最短路上的边,然后求解。不过这种做法最坏时间复杂度可以有,对于这道题数据范围较大,所以可以用更好写,思维难度也不高的方法来解决。

首先记录数组,分别表示到的最短路,次短路。设此时用更新,则我们分别考虑如何更新最短路和次短路,在就是本题求的是严格次短路,注意判断条件。具体见代码注释。

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;

int read(){
	int x=0,f=1;char ch=getchar();
	while(!isdigit(ch)){
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while(isdigit(ch)) x=x*10+ch-'0',ch=getchar();
	return x*f;
}

int n,m,head[N],tot,dist[N][2],vis[N];

struct node{
	int to,nxt,w;
}edge[N*2];
void add(int x,int y,int w){
	edge[++tot].to=y;
	edge[tot].w=w;
	edge[tot].nxt=head[x];
	head[x]=tot;
}

void spfa(int s){
	queue<int> q;
	memset(dist,0x3f,sizeof(dist)),memset(vis,0,sizeof(vis));
	q.push(s),dist[s][0]=0,vis[s]=1;
	while(!q.empty()){
		int t=q.front();q.pop();
		vis[t]=0;
		for(int i=head[t];i;i=edge[i].nxt){
			int y=edge[i].to;
			if(dist[y][0]>dist[t][0]+edge[i].w){//可以更新最短路
				dist[y][1]=dist[y][0];别忘了先更新y的次短路
				dist[y][0]=dist[t][0]+edge[i].w;
				if(!vis[y]) vis[y]=1,q.push(y);
			}
            //不能更新y的最短路,但可以用t的最短路更新y的次短路
			if(dist[y][1]>dist[t][0]+edge[i].w&&dist[t][0]+edge[i].w>dist[y][0]){
				dist[y][1]=dist[t][0]+edge[i].w;
				if(!vis[y]) vis[y]=1,q.push(y);//这时也要入队
			}
            //用t的次短路更新y的次短路
			if(dist[y][1]>dist[t][1]+edge[i].w){
				dist[y][1]=dist[t][1]+edge[i].w;
				if(!vis[y]) vis[y]=1,q.push(y);
			}
		}
	}
}

int main(){
	
	n=read(),m=read();
	for(int i=1;i<=m;i++){
		int x=read(),y=read(),w=read();
		add(x,y,w),add(y,x,w);
	}
	spfa(n);
	cout<<dist[1][1]<<endl;
	
	return 0;
}
相关推荐
jinyishu_2 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm2 小时前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
什巳3 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
hold?fish:palm5 小时前
RDB全量快照备份
c++·redis·后端
什巳5 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826525 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
盐焗鹌鹑蛋6 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
巧克力男孩dd6 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒7 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵7 小时前
第 2 章 顺序表和 vector
java·数据结构·算法