P3385 【模板】负环
作者:
多米尼克領主的致意
,
2024-05-30 10:04:52
,
所有人可见
,
阅读 7
只判点1的负环
code:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e3 + 10, M = 3e3 + 10;
int t;
int h[N], idx;
int cnt[N];
struct node
{
int to, ne, w;
}e[M * 2];
int dist[N], st[N];
void add(int a, int b, int c){
e[idx].to = b;
e[idx].w = c;
e[idx].ne = h[a];
h[a] = idx++;
}
void spfa(int n){
queue<int>q;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
q.push(1);
memset(st, 0, sizeof st);
st[1] = 1;
memset(cnt, 0, sizeof cnt);
while(q.size()){
auto t = q.front();
q.pop();
st[t] = false;
for(int i = h[t];~i;i = e[i].ne){
int j = e[i].to;
if(dist[j] > dist[t] + e[i].w){
dist[j] = dist[t] + e[i].w;
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n){
cout << "YES" << endl;
return;
}
if(!st[j]){
q.push(j);
st[j] = true;
}
}
}
}
cout << "NO" << endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> t;
while(t--){
idx = 0;
memset(h, -1, sizeof h);
int n, m;
cin >> n >> m;
for(int i = 1;i <= m;i++){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
if(c >= 0)add(b, a, c);
}
spfa(n);
}
return 0;
}