SPFA判断负环与SPFA求最短路不太一致,判断负环的基本思路是如果任意一点到当前点的距离是大于等于n的,由抽屉原理可得一定存在负环,这里dist表示任意一点到当前点的距离,这里不用初始化默认为0,因为负权边的存在,始终会进行最短距离的更新,cnt表示任意一点到当前点最短距离对应的边数。
    时间复杂度:Acwing852. SPFA判断负环 - 图1

    1. #include<iostream>
    2. #include<algorithm>
    3. #include<cstring>
    4. #include<queue>
    5. using namespace std;
    6. const int N = 1e5+100;
    7. int e[N],ne[N],h[N],w[N],idx;
    8. // dist表示任意一点到当前点的距离,cnt表示任意一点到当前点最短距离对应的边数
    9. int dist[N],cnt[N];
    10. // 标记是否在队列中
    11. bool st[N];
    12. int n,m;
    13. // 添加一条从a指向b,权为c的边
    14. void add(int a,int b,int c){
    15. e[idx] = b,ne[idx]= h[a],w[idx]= c, h[a] = idx++;
    16. }
    17. bool spfa(){
    18. // 这里区别于SPFA求最短路,这里不用初始化默认为0,因为负权边的存在,始终会进行最短距离的更新
    19. // memset(dist,0x3f,sizeof dist);
    20. // dist[1] = 0;
    21. queue<int> q;
    22. // 因为起点不一定是从1开始,如果把全部点都加到队列里面,肯定可以找到负环
    23. for(int i=1;i<=n;i++) {
    24. q.push(i); st[i] = true;
    25. }
    26. while(q.size()){
    27. // 弹出队头
    28. int t = q.front(); q.pop(); st[t] = false;
    29. // 遍历所有出边
    30. for(int i=h[t];i!=-1;i=ne[i]){
    31. int j = e[i];
    32. /// 更新距离
    33. if(dist[j]>dist[t]+w[i]){
    34. dist[j] = dist[t]+w[i];
    35. cnt[j] = cnt[t]+1;
    36. // 如果距离起点的边不小于n,那肯定有负权环
    37. if(cnt[j]>=n) return true;
    38. if(!st[j]){
    39. q.push(j); st[j] = true;
    40. }
    41. }
    42. }
    43. }
    44. return false;
    45. }
    46. int main(){
    47. cin >> n >> m;
    48. // 一定要初始化
    49. memset(h,-1,sizeof h);
    50. while(m--){
    51. int a,b,c;
    52. cin >> a >> b >> c;
    53. add(a,b,c);
    54. }
    55. if(spfa()) cout << "Yes" << endl;
    56. else cout << "No" << endl;
    57. return 0;
    58. }