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

相关推荐
凯瑟琳.奥古斯特13 分钟前
BFS解力扣1654最短跳跃次数
数据结构·算法·广度优先
sg_knight13 分钟前
第一次用 OpenClaw,我让它 3 分钟写了个小工具
算法·llm·agent·ai编程·openclaw
m0_6294947313 分钟前
LeetCode 热题 100-----23.反转链表
数据结构·算法·leetcode·链表
炸膛坦客18 分钟前
嵌入式 - 数据结构与算法:(1-10)排序算法 - 冒泡排序(Bubble Sort)
算法·排序算法
Hello eveybody27 分钟前
介绍一下动态树LCT(Python)
开发语言·python·算法
不穿铠甲的穿山甲30 分钟前
MMR最大边际相关性
算法
handler0132 分钟前
速通蓝桥杯省一:二分算法
c语言·开发语言·c++·笔记·算法·职场和发展·蓝桥杯
炽烈小老头33 分钟前
【 每天学习一点算法 2026/05/08】最小覆盖子串
学习·算法
汉克老师1 小时前
GESP5级C++考试语法知识(十六、分治算法(三))
c++·算法·分治算法·汉诺塔·逆序对·gesp5级·gesp五级
V搜xhliang02461 小时前
OpenClaw进阶完全教程
运维·人工智能·算法·microsoft·自动化