当前位置: 首页 > news >正文

P2865 [USACO06NOV] Roadblocks G

*原题链接*

次短路模版题

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

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

#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;
}


http://www.mrgr.cn/news/26926.html

相关文章:

  • Linux环境基础开发工具---vim
  • CSS 新特性查漏补缺,快来看看你用过几个?
  • cmake的出现是为了解决什么问题 cmake是干嘛的
  • 现代 Web 开发工具箱:Element-UI 表单组件全攻略(二)
  • 【docker】docker 关键技术 —— 镜像制作
  • [论文精读]Polarized message-passing in graph neural networks
  • 5分钟手把手系列(二):本地部署Graphrag(Pycharm+Ollama+LM Studio)
  • border制作渐变色边框
  • 我们来聊聊SOME/IP的timing时间参数和TTL(Time To Live)的作用及使用规则。
  • unordered系列模拟实现
  • 个人电脑可以当服务器用吗?
  • MyBatis解决实体类(POJO)的字段名和数据库表的列名不一致方法总结(四种方法)
  • 线程 - 线程的由来、进程和线程的关系、进程创建_等待_退出详解
  • Docker零基础入门
  • 爆品只是日百商家的表面“风光”
  • 最新热点!结合创新!小样本学习+CLIP:超好上手的思路,爽发顶会顶刊
  • react-intl——react国际化使用方案
  • 冯·诺依曼体系结构简介:计算机历史的奠基石
  • 软件安装攻略:EmEditor编辑器下载安装与使用
  • KTM580030bit 绝对角度细分器支持最多 4096 对极与一键非线性自校准集成双 16bit 2M SAR ADC