关于这道题我的上一篇题解 Spore里有对负环判断的解释,可以跳转进行研究。这里只贴出代码。。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxn=2010;
const int maxm=3010;
int head[maxn],nnext[maxm*2],to[maxm*2],length[maxm*2],team[maxn],cnt[maxn],dis[maxn];
bool b[maxn];
int tot,tt,n,m;
int s,t;
void add(int x,int y,int l)
{
tot++;
nnext[tot]=head[x];
head[x]=tot;
to[tot]=y;
length[tot]=l;
}
bool spfa(int x)
{
for(int i=1;i<=n;i++)
{
dis[i]=1e9;
}dis[1]=0;
team[t]=1;
t++;
b[1]=true;
cnt[1]=1;
while(s!=t)
{
int now=team[s];
s++;
s%=n;
b[now]=false;
for(int i=head[now];i;i=nnext[i])
{
int y=to[i];
if(dis[y]>dis[now]+length[i])
{
dis[y]=dis[now]+length[i];
if(b[y]==false)
{
team[t]=y;
t++;
t%=n;
b[y]=true;
cnt[y]=cnt[now]+1;
if(cnt[y]>n) return true;
}
}
}
}
return false;
}
int main()
{
cin>>tt;
while(tt--)
{
s=0,t=0,tot=0;
memset(head,0,sizeof(head));
memset(team,0,sizeof(team));
memset(b,false,sizeof(b));
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
if(z<0)
{
add(x,y,z);
}
else
{
add(x,y,z);
add(y,x,z);
}
}
bool ff=spfa(1);
if(ff==true) cout<<"YE5"<<endl;
else cout<<"N0"<<endl;
}
return 0;
}