cnt数组计算入队次数,一个点入队次数多于n就有负环
注意每组数据要重新初始化所有数组!因为落下一个head数组就全TLE了qwq
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#define maxn 20001
#define INF 100000001
using namespace std;
int T, n, m, tot;
int head[maxn], dis[maxn], cnt[maxn], vis[maxn];
struct edge{
int nxt, to, val;
}e[60001];
void add(int u, int v, int w){
e[++tot].nxt=head[u];
e[tot].to=v;
e[tot].val=w;
head[u]=tot;
}
int SPFA(){
for(int i=1; i<=n; i++)
vis[i]=0,dis[i]=INF;
memset(cnt, 0, sizeof(cnt));
queue<int> q;
q.push(1);
vis[1]=1;dis[1]=0;cnt[1]=1;
while(!q.empty()){
int u=q.front();
q.pop();
vis[u]=0;
if(cnt[u]>n)return 1;
for(int i=head[u]; i; i=e[i].nxt){
int v=e[i].to;
if(dis[v]>dis[u]+e[i].val){
dis[v]=dis[u]+e[i].val;
cnt[v]=cnt[u]+1;
if(cnt[v]>n)return 1;
if(!vis[v]){
vis[v]=1;
q.push(v);
}
}
}
}
return 0;
}
int main(){
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &m);
memset(head, 0, sizeof(head));
int g, h, j;
tot=0;
for(int i=1; i<=m; i++){
scanf("%d%d%d", &g, &h, &j);
add(g, h, j);
if(j>=0)add(h, g, j);
}
puts(SPFA()?"YE5":"N0");
}
return 0;
}