文章目录
前言
一、什么是spfa算法
二、例题,代码
1.AcWing 851. spfa求最短路
本题分析
AC代码
2.AcWing 852. spfa判断负环
本题分析
AC代码
三、时间复杂度
前言
复习acwing算法基础课的内容,本篇为讲解基础算法:spfa,关于时间复杂度:目前博主不太会计算,先鸽了,日后一定补上。
一、什么是spfa算法
计算最短路算法的一种,spfa算法可以说是bellman-ford算法的算法优化版本,相较于Dijkstra算法,它可以计算有负权边的最短路,下图来自ACWing算法基础课,关于Dijkstra算法的详细讲解,见博客:Dijkstra,关于bellman-ford算法见博客:bellman-ford
二、例题,代码
1.AcWing 851. spfa求最短路
本题链接:AcWing 851. spfa求最短路
本博客提供本题截图:
本题分析
我们的spfa算法是在bellman-ford算法的基础上进行了优化,所以在这里只讲解优化部分,具体的其他部分的含义,详细见博客:bellman-ford
在bellman-ford算法中我们会遍历所有的边,但是很多的边的遍历是没有意义的,通过对bellman-ford算法的算法核心进行观察我们会发现:
for (int i = 0; i < k; i ++ ) { memcpy(backup, dist, sizeof dist); for (int j = 0; j < m; j ++ ) { auto t = eg[j]; dist[t.b] = min(dist[t.b], backup[t.a] + t.w); } }
对dist数组的更新中,dist[t.b]的更新是因为dist[t.a]的更新,故根据这一点,我们没必要遍历所有的边,只有当这个点更新后,后续的点才会更新,考虑到这里,我们创建一个队列(STL),把我们每一次更新的点加入到队列中.关于队列的详细讲解见博客:STL—queue,关于手写队列,见博客:用数组模拟队列
AC代码
#include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; const int N = 100010; int n, m; int h[N], w[N], e[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 ++ ; } 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; 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; } } } } return dist[n]; } int main() { scanf("%d%d", &n, &m); memset(h, -1, sizeof h); while (m -- ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); } int t = spfa(); if (t == 0x3f3f3f3f) puts("impossible"); else printf("%d\n", t); return 0; }
2.AcWing 852. spfa判断负环
本题链接:AcWing 852. spfa判断负环
本博客给出本题截图
本题分析
本题中我们用cnt数组去记录边数,cnt[i]表示的是从第一个点到第i个点有多少条边,我们知道,n个点的话最多有n - 1条边,如果某一个点的cnt ≥ n的话,那么就可以证明一定存在负权回路,和第一道例题不同的是,我们不能只把第一个点加入到我们的queue中,因为可能第一个点的路径中没有负权回路,别的点的路径中有,所以我们需要把所有的点都加入到queue中.
AC代码
#include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; const int N = 2010, M = 10010; int n, m; int h[N], w[M], e[M], ne[M], idx; int dist[N], cnt[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 ++ ; } bool spfa() { queue<int> q; for (int i = 1; i <= n; i ++ ) { st[i] = true; q.push(i); } 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; } } } } return false; } int main() { scanf("%d%d", &n, &m); memset(h, -1, sizeof h); while (m -- ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); } if (spfa()) puts("Yes"); else puts("No"); return 0; }
三、时间复杂度
关于spfa算法的时间复杂度以及证明,后续会给出详细的说明以及证明过程,目前先鸽了。