简介
SPFA 算法是 Bellman-Ford算法 的队列优化算法的别称,通常用于求含负权边的单源最短路径,以及判负权环。SPFA 最坏情况下时间复杂度和朴素 Bellman-Ford 相同,为 O(VE)。
代码
求最短路版(和dijkstra堆优化有点类似)
//spfa求最短路
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, 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> qu;
qu.push(1);
st[1] = true;
while (!qu.empty())
{
int t = qu.front();
qu.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])
{
st[j] = true;
qu.push(j);
}
}
}
}
return dist[n];
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
spfa();
if (dist[n] == 0x3f3f3f3f)
puts("impossible");
else
cout << dist[n] << endl;
return 0;
}
判断负环版
我们需要注意的是加上判断负环的话,时间复杂度可能就会比较高
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, dist[N], cnt[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()
{
queue<int> qu;
for(int i = 1; i <= n; i++)//因为是判断图中是否存在负环,而不是看单一的点,故而在遍历的时候我们首先要把所有的点都放到队列中
{
st[i] = true;
qu.push(i);
}
while (!qu.empty())
{
int t = qu.front();
qu.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;//(抽屉原理,当cnt>=n时一定遍历了大于等于n+1个点,由抽屉原理可知一定重复遍历了一些点,那么就存在负环)
if (!st[j])
{
st[j] = true;
qu.push(j);
}
}
}
}
return false;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
if (spfa())
puts("Yes");
else
puts("No");
return 0;
}