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

相关推荐
LYFlied9 小时前
【每日算法】LeetCode 153. 寻找旋转排序数组中的最小值
数据结构·算法·leetcode·面试·职场和发展
唐装鼠9 小时前
rust自动调用Deref(deepseek)
开发语言·算法·rust
ytttr87310 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
jianfeng_zhu11 小时前
整数数组匹配
数据结构·c++·算法
smj2302_7968265211 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
LYFlied12 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-13 小时前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄13 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳13 小时前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang13 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽