SPFA算法(对bellman - ford的优化)(适用于负权边且不能有负权回路)
一般情况下spfa算法也可以解决正权边问题,且时间比Dijkstrsa更快(但是如果出题人卡掉了spfa算法,就只能用Dijkstrsa算法了)
上一篇博客介绍了bellman_ford算法,建议两个算法一起看
区别:bellman_ford算法更新每一个点,而spfa算法只更新变小的点。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int n,m;
int h[N] , e[N] , w[N] , ne[N] , idx;
int dist[N];
bool st[N];
void add(int a , int b , int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
void spfa()
{
queue<int>q;//存储每次更新的所有的点
dist[1] = 0;
q.push(1);
st[1] = true;
while(!q.empty())
{
int t = q.front();//每次从队列取出一个来更新所有它能够到达的点
q.pop();
st[t] = false;
for(int i = h