求解,下面是我的代码
// luogu-judger-enable-o2
#ifndef _SPFA
#define _SPFA 2018.6.11
# include <cstdio>
# include <iostream>
# include <queue>
# include <cstring>
# define _cin std::ios::sync_with_stdio(0)
# define INF 0x7fffffff
# define rg register int
# define il inline
# define N 1000000
using namespace std;
struct edge
{
int next;
int to;
int w;
}e[(N+1)<<1];
int head[N+1];
int book[N+1];
int dis[N+1];
int edge_sum=0;
int n,m;
template <class T> il bool SPFA(T s);
template <class A> il void add_edge(A &u,A &,A &w);
int main()
{
_cin;
cin.tie();
rg t;
cin>>t;
while(t--)
{
edge_sum=0;
rg u,v,w;
memset(head,0,sizeof(head));
memset(dis,0x7f,sizeof(dis));
memset(book,0,sizeof(book));
cin>>n>>m;
for(rg i = 1;i<=m;i++)
{
edge_sum++;
cin>>u>>v>>w;
e[edge_sum].next=head[u];
e[edge_sum].to=v;
e[edge_sum].w=w;
head[u]=edge_sum;
if(w >= 0)
{
edge_sum++;
e[edge_sum].next=head[v];
e[edge_sum].to=u;
e[edge_sum].w=w;
head[v]=edge_sum;
}
}
if(SPFA(1)) cout<<"YE5"<<endl;
else cout<<"N0"<<endl;
}
return 0;
}
template <class A> il void add_edge(A &u,A &v,A &w)
{
edge_sum++;
e[edge_sum].next=head[u];
e[edge_sum].to=v;
e[edge_sum].w=w;
head[u]=edge_sum;
return;
}
template <class T> il bool SPFA(T s)
{
queue <int> a;
dis[s]=0;
a.push(s);
book[s]=1;
while(a.size()>0)
{
int k=a.front();
a.pop();
book[k]=0;
for(int i = head[k];i;i=e[i].next)
{
if(dis[k] < INF and dis[e[i].to]>dis[k]+e[i].w)
{
dis[e[i].to]=dis[k]+e[i].w;
if(e[i].to == s) return true;
if(!book[e[i].to])
{
a.push(e[i].to);
book[e[i].to]=1;
}
}
}
}
return false;
}
#endif