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

相关推荐
爱理财的程序媛2 小时前
openclaw 盯盘实践
算法
MobotStone6 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法
颜酱9 小时前
队列练习系列:从基础到进阶的完整实现
javascript·后端·算法
用户5757303346249 小时前
两数之和:从 JSON 对象到 Map,大厂面试官到底在考察什么?
算法
程序猿追9 小时前
“马”上行动:手把手教你基于灵珠平台打造春节“全能数字管家”
算法
ZPC82101 天前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82101 天前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David1 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱1 天前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc