负环

原理

见《进阶指南》第391页。

模板题

洛谷-P3385-【模板】负环open in new window

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 2010, M = 3010;
struct edge {
    int to, next, w;
};
edge e[2 * M];
int idx, head[N];
int n, m;
int dis[N], cnt[N];
bool mark[N];

void add_edge (int u, int v, int w) {
    e[idx].w = w;
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
bool spfa () {
    memset(mark, 0, sizeof(mark));
    memset(cnt, 0, sizeof(cnt));
    memset(dis, 0x3f, sizeof(dis));

    queue<int> q;
    dis[1] = 0;
    q.push(1);
    mark[1] = true;
    while (!q.empty()) {
        int cur = q.front();
        q.pop();
        mark[cur] = false;
        for (int i = head[cur]; i != -1; i = e[i].next) {
            int to = e[i].to, w = e[i].w;
            if (dis[cur] + w < dis[to]) {
                dis[to] = dis[cur] + w;
                cnt[to] = cnt[cur] + 1;
                if (cnt[to] >= n) return true;
                if (mark[to] == false) {
                    q.push(to);
                    mark[to] = true;
                }
            }
        }
    }
    return false;
}

int main () {
    int T;
    scanf("%d", &T);
    while (T --) {
        idx = 0;
        memset(head, -1, sizeof(head));
        scanf("%d%d", &n, &m);
        for (int i = 1, u, v, w; i <= m; ++ i) {
            scanf("%d%d%d", &u, &v, &w);
            add_edge(u, v, w);
            if (w >= 0) add_edge(v, u, w);
        }
        
        printf(spfa() ? "YES\n" : "NO\n");
    }
    return 0;
}
最后修改于: