Spfa求负环
介绍
求负环方法
求负环的常用方法,基于 \(SPFA\),一般都用方法 \(2\):
方法 \(1\):统计每个点入队的次数,如果某个点入队 \(n\) 次,则说明存在负环
方法 \(2\):统计当前每个点的最短路中所包含的边数,如果某点的最短路所包含的边数大于等于 \(n\),则也说明存在环
原理
在使用 \(SPFA\) 求负环的时候,我们不能像求最小生成树一样,随便往队列中加入一个起点,因为图可能不连通,也就是说,图中存在负环,但不在这个连通块上。
比较暴力的一种做法是暴力枚举每一个起点,但这样的时间复杂度显然是无法接受的。
不过,对于这种多起点的问题,我们有一种很方便的解决方法:虚拟源点。我们建立一个虚拟源点(不一定是真实的,下面会解释),让这个虚拟源点指向所有点,这样,我们就通过这个虚拟远点把所有连通块连接在一起了。
此时,只要存在环,那么这个环必然包含虚拟源点。因为在我们 \(SPFA\) 第一次迭代的时候,会将所有点的距离更新并将所有点插入队列中。因此,我们就有两种写法:
- 创建真实的虚拟源点,并创建由虚拟源点到所有点的边,初始时只将虚拟源点加入队列
- 创建虚假的虚拟源点,初始时将所有点加入队列,其实就是在真实的虚拟源点的基础上预先进行了一次 \(SPFA\) 的迭代而已。
模板
1.真实的虚拟源点
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 2e3 + 10, M = 2e4 + 10;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N];
int cnt[N];
bool st[N];
bool spfa()
{
memset(dist, 0x3f, sizeof dist);
dist[0] = 0;
queue<int> q;
q.push(0);
st[0] = 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])
{
cnt[j] = cnt[t] + 1;
if(cnt[j] > n) return true;
dist[j] = dist[t] + w[i];
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
void add(int a, int b, int c) // 添加一条边a->b,边权为c
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
while(m -- )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
for(int i = 1; i <= n; i ++ ) add(0, i, 0);
if(spfa()) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
2.虚假的虚拟源点
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 2e3 + 10, M = 2e4 + 10;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N];
int cnt[N];
bool st[N];
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])
{
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n) return true;
dist[j] = dist[t] + w[i];
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
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()) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
注意的点
1.更新路径出错
在 \(SPFA\) 迭代的过程中,如果我们更新了一个点,那么这个点所在的最短路的边数必然被更新
其中,正确的更新方法是:cnt[j] = cnt[t] + 1;
而不是:cnt[j] ++ ;
2.dist[] 数组
在 \(SPFA\) 求负环的时候,理论上是不需要初始化 \(dist[]\) 的,因为无论 \(dist[i]\) 是多少,只要存在负环,那么它就会不断被更新,但是为了规范和统一,还是尽量初始化一个合适的最大值。