当前位置:网站首页>spfa AcWing 851. spfa求最短路
spfa AcWing 851. spfa求最短路
2022-07-02 09:43:00 【T_Y_F666】
spfa AcWing 851. spfa求最短路
原题链接
算法标签
最短路 spfa
思路
求最短路算法汇总
该图摘自该视频
spfa算法是对Bellman_ford算法的优化
Bellman_ford算法会遍历所有的边,但是有很多的边遍历了其实没有什么意义,我们只用遍历那些到源点距离变小的点所连接的边即可,只有当一个点的前驱结点更新了,该节点才会得到更新;因此考虑到这一点,我们将创建一个队列每一次加入距离被更新的结点。
该图摘自该题解
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
int h[N], e[N], ne[N], w[N], idx;
int dis[N];
bool st[N];
int n,m;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
void add(int a, int b, int c){
e[idx]=b;
w[idx]=c;
ne[idx]=h[a];
h[a]=idx++;
}
int sp(){
memset(dis, 0x3f, sizeof dis);
dis[0]=1;
queue<int> q;
q.push(1);
st[1]=true;
while(q.size()){
int t=q.front();
q.pop();
// 从队列中取出来之后该节点st被标记为false,代表之后该节点如果发生更新可再次入队
st[t]=false;
for(int i=h[t];i!=-1;i=ne[i]){
int j=e[i];
if(dis[j]>dis[t]+w[i]){
dis[j]=dis[t]+w[i];
if(!st[j]){// 当前已经加入队列的结点,无需再次加入队列,即便发生了更新也只用更新数值即可,重复添加降低效率
q.push(j);
st[j]=true;
}
}
}
}
return dis[n];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(h, -1, sizeof h);
n=read(), m=read();
while(m--){
int x=read(), y=read(), z=read();
add(x, y, z);
}
if(sp()==0x3f3f3f3f){
puts("impossible");
}else{
printf("%lld\n", sp());
}
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
边栏推荐
猜你喜欢

Enhance network security of kubernetes with cilium

Embedded Software Engineer career planning

线性DP AcWing 897. 最长公共子序列

Tas (file d'attente prioritaire)

Find the common ancestor of any two numbers in a binary tree

drools动态增加、修改、删除规则

Simple use of drools decision table

mysql索引和事务

MySQL and PostgreSQL methods to grab slow SQL

模块化 CommonJS ES Module
随机推荐
Leetcode209 subarray with the smallest length
(C language) input a line of characters and count the number of English letters, spaces, numbers and other characters.
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
排序---
drools执行String规则或执行某个规则文件
Gaode map test case
"As a junior college student, I found out how difficult it is to counter attack after graduation."
中国交通标志检测数据集
OpenCV中cv2.VideoWriter_fourcc()函数和cv2.VideoWriter()函数的结合使用
趣味 面试题
计数类DP AcWing 900. 整数划分
Lombok common annotations
mysql数据库基础
(C language) 3 small Codes: 1+2+3+ · · +100=? And judge whether a year is a leap year or a normal year? And calculate the circumference and area of the circle?
Docker compose configuration mysql, redis, mongodb
drools中then部分的写法
Distributed machine learning framework and high-dimensional real-time recommendation system
CDA数据分析——Excel数据处理的常见知识点归纳
线性DP AcWing 897. 最长公共子序列
CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function