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 小时前
深度优先算法学习
学习·算法·深度优先
GalaxyPokemon2 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
hn小菜鸡3 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX3 小时前
分享今天做的力扣SQL题
sql·算法·leetcode
music&movie4 小时前
算法工程师认知水平要求总结
人工智能·算法
laocui15 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910135 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥6 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥6 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu6 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode