SPFA 算法可以求单源负权边的最短路问题,时间复杂度最坏$O(nm)$, 一般是$O(n)$。SPFA求最短路的时候不能有负环,但是可以利用SPFA判断是否有负环。
算法基本流程, 流程和BFS有点类似:
- 首先创建一个队列,然后起点入队列。
- 然后每次出队列,扩展队列,更新距离最小值
- 最后输出最短距离
AcWing 851. spfa求最短路
来源: https://www.acwing.com/problem/content/853/
给定一个n个点m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出impossible。
数据保证不存在负权回路。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出”impossible”。
数据范围
$1≤n,m≤10^5 ,$
图中涉及边长绝对值均不超过10000。
输入样例:
输出样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <iostream> #include <cstring> #include <algorithm> #include <queue>
using namespace std; const int N = 100010, INF = 0x3f3f3f3f; int h[N], e[N], ne[N], w[N], idx; int dist[N]; bool st[N]; int n, m;
int spfa() { memset(dist, 0x3f, sizeof dist); dist[1] = 0; queue<int> q; q.push(1);
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]; }
void add(int a, int b, int c) { e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++; }
int main() { cin >> n >> m; memset(h, -1, sizeof h); while(m--) { int a, b, c; cin >> a >> b >> c; add(a, b, c); }
int u = spfa(); if (u == INF) puts("impossible"); else cout << u << endl; return 0; }
|
AcWing 852. spfa判断负环
来源: https://www.acwing.com/problem/content/854/
给定一个n个点m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你判断图中是否存在负权回路。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
如果图中存在负权回路,则输出“Yes”,否则输出“No”。
数据范围
$1≤n≤2000,$
$ 1≤m≤10000,$
图中涉及边长绝对值均不超过10000。
输入样例:
输出样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include <iostream> #include <cstring> #include <algorithm> #include <queue>
using namespace std; const int N = 2100, M = 10010; int h[N], ne[M], e[M], w[M], idx;
int dist[N], cnt[N]; bool st[N]; int n, m;
bool spfa() {
queue<int> q; for( int i = 1; i <= n; i++) { q.push(i); st[i] = 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]; cnt[j] = cnt[t] + 1; if (cnt[j] == n) return true; if (!st[j]) { q.push(j); st[j] = true; } } } } return false; }
void add(int a, int b, int c) { e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++; }
int main() { cin >> n >> m; memset(h, -1, sizeof h); while(m--) { int a, b, c; cin >> a >> b >> c; add(a, b, c); }
if(spfa()) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
|