#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
struct node
{
int v,w,next;
}e[200005];
int first[200005],k;
int vis[20005],dis[20005],cnt[20005];
int t,n,m;
int read()
{
int x=0,fu=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-') fu=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=(x<<3)+(x<<1)+c-'0';
c=getchar();
}
return x*fu;
}
void add(int u1,int v1,int w1)
{
e[++k].v=v1; e[k].w=w1; e[k].next=first[u1]; first[u1]=k;
}
int spfa()
{
queue <int> q;
dis[1]=0; cnt[1]=1; q.push(1); vis[1]=1;
while(!q.empty())
{
int u1=q.front(); q.pop();
vis[u1]=0;
for(int i=first[u1];i;i=e[i].next)
{
int v1=e[i].v,w1=e[i].w;//问题中的v1
if(dis[v1]>dis[u1]+w1)
{
dis[v1]=dis[u1]+w1;
cnt[v1]=cnt[u1]+1;
if(cnt[v1]>n) return 1;//在我本机上运行时曾尝试输出此处此时的i,v1,结果i=first[4]=-1,v=0;
if(!vis[v1])
{
q.push(v1); vis[v1]=1;
}
}
}
}
return 0;
}
int main()
{
t=read();
while(t--)
{
n=read(); m=read(); k=0;
memset(first,-1,sizeof(first));
memset(dis,0x3f3f3f3f,sizeof(dis));
memset(vis,0,sizeof(vis));
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=m;++i)
{
int ui=read(),vi=read(),wi=read();
add(ui,vi,wi);
if(wi>=0) add(vi,ui,wi);
}
if(spfa()) printf("YES\n");
else printf("NO\n");
}
return 0;
}
我这个代码在spfa中神奇地出现了v1=0,for中i=-1仍继续运行等神奇情况,希望有dalao可以帮忙指正是哪里的问题 (附上wa的数据 in:
1
4 6
1 2 -3
1 3 -2
1 4 -1
2 3 -6
2 4 -5
3 4 -4
out:NO 我的输出:YES