【模板】负环 - 洛谷https://www.luogu.com.cn/problem/P3385
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
#include <cstdlib>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int n, m;
int head[MAXN];
int nxt[MAXN];
int ver[MAXN];
int cost[MAXN];
int cnt;
int num[MAXN];
int d[MAXN];
inline void add(int x, int y, int c) {
ver[++cnt] = y;
cost[cnt] = c;
nxt[cnt] = head[x];
head[x] = cnt;
}
bool vis[MAXN];
inline void spfa() {
memset(vis, 0, sizeof(vis));
memset(d, 0x3f, sizeof(d));
memset(num, 0, sizeof(num));
d[1] = 0;
queue<int> que;
que.push(1);
vis[1] = true;
while (!que.empty()) {
int x = que.front();
que.pop();
vis[x] = false;
for (int i = head[x]; i; i = nxt[i]) {
int y = ver[i], c = cost[i];
if (d[y] > d[x] + c) {
d[y] = d[x] + c;
num[y] = num[x] + 1;
if (num[y] > n) {
printf("YES\n");
return;
}
if (!vis[y]) {
vis[y] = true;
que.push(y);
}
}
}
}
printf("NO\n");
}
int main() {
int t;
int x, y, c;
scanf("%d", &t);
while (t--) {
memset(head, 0, sizeof(head));
// memset(nxt,0,sizeof(nxt));
cnt = 0;
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d %d %d", &x, &y, &c);
if (c >= 0) {
add(x, y, c);
add(y, x, c);
} else {
add(x, y, c);
}
}
spfa();
}
return 0;
}