天天看點

acwing 852 spfa判斷負環

題面

acwing 852 spfa判斷負環

題解

  1. 原理:我們可以用一個cnt[t] 來記錄點1 - t 經過的點數,那麼每次拿t來更新其他點 j 的最小距離時,cnt[j] =cnt[t]+1 (1—>t—>j) ,那麼當cnt[j]>=n,表示1-j之間(包括自己)最少有n+1個點,肯定是不合法的
  1. 為什麼會出現cnt[j]>=n這種情況呢,就是因為圖中存在負環,每次經過負環dist都會變小,是以會一直更新,那麼cnt[j]就是一直變大超出n

代碼

#include<bits/stdc++.h>

using namespace std;
const int N = 1e5 + 10;

int n, m;
int h[N], e[N], w[N], ne[N], 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() {
    //不需要初始化dist(因為這個隻是需要判斷dist有沒有減小,存在負環的話,沒循環一次都會減小)
    queue<int> q;
    //這裡要把每個點都放入,因為負環有可能是1号點到達不了的
    for (int i = 1; i <= n; i++) {
        q.push(i);
        st[i] = true;
    }

    while (q.size()) {
        auto 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() {

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    memset(h, -1, sizeof h);

    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    if(spfa()) cout<<"Yes"<<endl;
    else cout<<"No"<<endl;

    return 0;
}
           

繼續閱讀