SPFA算法-邻接表存图

【算法简介】
SPFA 算法是Bellman-Ford算法的队列优化算法的别称,通常用于求含负权边的单源最短路径,以及判负权环。
SPFA算法通过判断图中是否存在一个顶点入队次数超过顶点总数n,来判断图中是否存在负权环。

最短路径算法中普遍使用的松弛操作的原理源自于著名的定理:“三角形两边之和大于第三边”
在数学及信息学中,我们称它为三角不等式。
所谓对结点i,j进行松弛,就是判定是否成立dis[j]>dis[i]+w[i,j],如果成立则令dis[j]=dis[i]+w[i,j],否则不变。

SPFA算法实现思路:
首先建立一个队列。初始时,队列里只有起始点。
其次建立一个表格存储起始点到图中所有点的最短路径(开始时,起始点到其他所有点的最短路径初始化为无穷大,到自身的最短路径初始化为0)。

然后执行松弛操作。用队列里的点去松弛起始点到图中所有点的最短路径,如果更新成功且被更新点不在队列中,则把该点入队。
重复执行直到队列为空。


【程序代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=500001;
const int inf=0x3f3f3f3f;

int vis[maxn];
int dis[maxn];

struct edge {
	int to;
	int w;   //weight
};
vector<edge> vec[maxn];

void SPFA(int start, int end) {
	memset(vis,0,sizeof(vis));
	memset(dis,inf,sizeof(dis));
	vis[start]=1;
	dis[start]=0;

	queue<int> Q;
	Q.push(start);

	while(!Q.empty()) {
		int cur=Q.front();
		Q.pop();
		vis[cur]=0;

		for(int i=0; i<vec[cur].size(); i++) {
			int to=vec[cur][i].to;
			int w=vec[cur][i].w;
			if(dis[to]>dis[cur]+w) { //Edge Relaxation
				dis[to]=dis[cur]+w;
				if(!vis[to]) {
					Q.push(to);
					vis[to]=1;
				}
			}
		}
	}

	cout<<dis[end]<<endl;
}

int main() {
	int n,m; //n:number of nodes,m:number of edges
	cin>>n>>m;

	//for(int i=1; i<=n; i++)	vec[i].clear();

	int s; //s:index of starting point in directed edge
	for(int i=0; i<m; i++) { //save graph
		edge e;
		cin>>s>>e.to>>e.w;
		vec[s].push_back(e);
	}

	int fir,las;
	cin>>fir>>las;
	SPFA(fir,las);

	return 0;
}


/*
in1:
3 3
1 2 -1
2 3 -1
3 1 2
3 1

out1:
2
-------------
in2:
5 5
4 3 1
3 0 5
3 1 -7
0 1 3
1 2 6
4 1

out2:
-6
*/



【参考文献】
https://blog.csdn.net/SDUTyangkun/article/details/88373067
https://www.cnblogs.com/shadowland/p/5870640.html
https://www.cnblogs.com/xzxl/p/7246918.html
https://blog.csdn.net/qq_41755258/article/details/84921910
https://blog.csdn.net/McDonnell_Douglas/article/details/54379641
https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值