代码如下
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 20010,M = 3010;
int T,n,m;
int h[N],w[N],e[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;
}
void init()
{
for(int i=0;i<N;i++)
{
ne[i]=0;
h[i]=0;
}
idx=0;
}
bool spfa()
{
memset(dist,0x3f,sizeof dist);
memset(cnt,0,sizeof cnt);
memset(st,false,sizeof st);
queue <int> q;
dist[1]=0;
st[1]=true;
q.push(1);
while(!q.empty())
{
int t=q.front();
q.pop();
st[t]=false;
for(int i=h[t];i;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;
//cout<<cnt[j]<<" ";
if(cnt[j]>=n){return true;}
if(!st[j])
{
q.push(j);
st[j]=true;
}
}
}
}
return false;
}
int main()
{
scanf("%d",&T);
while(T--)
{
init();
scanf("%d%d", &n, &m);
for(int i =1;i<=m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
if(w>=0) add(b,a,c);
}
if(spfa())
{
puts("YES");
}
else
{
puts("NO");
}
}
return 0;
}