spfa判断负环

235 阅读1分钟

题目思路

与SPFA求最短路径不同,SPFA判断负环需要一个记录最短边数的cnt数组,并在初始时将所有点入队

  1. 将所有点入队,因为不能够确定从1开始出发,一定能走到负环里,题目要求判断整个图是否存在负环。将所有点入队后,一定能够找到某个位置是否出现负环。
  2. 不需要初始化dist数组,因为如果存在负环,dist数组一定会被更新,我们只需要判断是否更新,不考虑距离。
  3. cnt数组,若发生了更新,就在结点j和节点t之间增加一条边。如果cnt大于n,根据抽屉原理,至少存在两个相同的点,则存在负环。
  4. 全部结束后,仍然没有cnt大于n的情况,则不存在负环,输出对应字符串。

C++代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>

using namespace std;

const int N = 2010, M = 10010;

int n, m;
int h[N], e[M], w[M], ne[M], idx;
int dist[N], cnt[N];
int st[N];

void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx;
    idx++;
}

void 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)
                {
                    cout << "Yes";
                    return;
                }
                if (!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    cout << "No";
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);

    memset(h, -1, sizeof h);

    cin >> n >> m;
    while (m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    spfa();
    return 0;
}