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;
}
相关推荐
MaTF_6 分钟前
《Effective C++》第三版——让自己习惯C++
开发语言·c++
ling1s11 分钟前
C#基础(12)递归函数
开发语言·算法·c#
Antonio91515 分钟前
【高级数据结构】树状数组
数据结构·c++·算法
大晴的上分之旅23 分钟前
树和二叉树基本术语、性质
数据结构·算法·二叉树
羊十一41 分钟前
C++(C++的文件I/O)
开发语言·c++·cocoa
Chase-Hart1 小时前
【每日一题】LeetCode 815.公交路线(广度优先搜索、数组、哈希表)
数据结构·算法·leetcode·散列表·宽度优先
Am心若依旧4091 小时前
[C++进阶[六]]list的相关接口模拟实现
开发语言·数据结构·c++·算法·list
人才程序员1 小时前
CSP-J 算法基础 广度优先搜索BFS
数据结构·c++·算法·深度优先·宽度优先·比赛·noi
GZK.1 小时前
【Leetcode】70. 爬楼梯
算法·leetcode·动态规划
敲代码的奥豆2 小时前
C++:日期类的实现
开发语言·c++