acwing搜索与图论(二)spfa

cpp 复制代码
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using  namespace std;
typedef pair<int, int> PII;
const int N=10010;
int n,m;
int h[N],e[N],ne[N],w[N],idx;
int dist[N];
bool st[N];


void add(int a,int b,int c){
	e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;	
}

int spfa(){
	memset(dist,0x3f,sizeof dist);
	dist[1]=0;
	queue <int > q;
	q.push(1);
	st[1]=true;
	
	while(q.size()){
		int t=q.front();
		q.pop();
		st[t]=false;
		if(!st[t]){
			for(int i=h[t];i!=-1;i=ne[i]){
				int j=e[i];
				if(dist[j]>dist[t]+w[i]){
					dist[j]=dist[t]+w[i];
					if(!st[j])
					{q.push(j);
						st[j]=true;
					
					}
					
				}
			}
		}
	}
	
	if(dist[n]==0x3f3f3f3f)return -1;
	return dist[n];
}
int main(){
	cin>>n>>m;
	memset(h,-1,sizeof h);
	while(m--){
		int a,b,c;
		cin>>a>>b>>c;
		add(a,b,c);
	}
	
	int t=spfa();
	
	if(t==-1)puts("imp");
	else printf("%d",t);
	return 0;
	
}

其实整体框架跟dijkstra的算法是差不多,是根据谁更新了,采取更新它的后继结点,时间复杂度一般是m,最坏的情况是nm

相关推荐
weixin_4461224640 分钟前
LinkedList剖析
算法
百年孤独_2 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程2 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生2 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生2 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode
岁忧2 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
alphaTao2 小时前
LeetCode 每日一题 2025/6/30-2025/7/6
算法·leetcode·职场和发展
ゞ 正在缓冲99%…2 小时前
leetcode67.二进制求和
算法·leetcode·位运算
YuTaoShao2 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II——排除法
java·算法·leetcode