SPFA算法是对Bellman_ford算法的优化。在最优情况下。在Bellman_ford算法中每次对所有边进行遍历,会造成大量的浪费。
SPFA算法中已经遍历的点可以再次入队,因此可以检测负环(如果存在负环会一直循环下去)
同样在时间允许的条件下SPFA算法也可以用于替换Dijkstra算法。(总之就是万能)
算法思想
Bellman_ford算法会遍历所有的边
,但是有很多的边遍历了其实没有什么意义,我们只用遍历那些到源点距离变小的点所连接的边即可
,只有当一个点的前驱结点更新了,该节点才会得到更新;因此考虑到这一点,我们将创建一个队列每一次加入距离被更新的结点。
bellman-ford算法操作如下:
for n次
for 所有边 a,b,w (松弛操作)
dist[b] = min(dist[b],back[a] + w)
spfa算法对第二行中所有边
进行松弛操作进行了优化,原因是在bellman—ford算法中,即使该点的最短距离尚未更新过,但还是需要用尚未更新过的值去更新其他点
,由此可知,该操作是不必要的,我们只需要找到更新过的值去更新其他点即可。
算法步骤
当队列不为空时:
1. 取出队头元素t
,并将状态标记为false
,表示之后该节点若发生更新可再次入队
2. 使用取出的节点t
更新其他节点,如果节点距离可悲更新,且尚未更新,则将节点入队,并标记状态为true
.
3. 重复步骤2
核心代码
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false; //从队列中取出来之后该节点st被标记为false,代表之后该节点如果发生更新可再次入队
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;
}
}
}
}
完整代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef pair<int, int> PII; //<离起点的距离, 节点编号>
const int N = 150010;
int h[N], e[N], ne[N], idx, w[N];
int dist[N];
bool st[N];
int n, m;
//在a节点之后插入一个b节点,权重为c
void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
int spfa()
{
memset(dist, 0x3f3f3f3f, 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;
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() {
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
if (spfa() == -1) cout << "impossible" << endl;
else
cout << spfa() << endl;
return 0;
}
使用SPFA判断是否存在负环
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
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];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}