SPFA判負環
馬上就退役了,時間不足就不多介紹了
反正DFS是會T飛的,BFS就沒關係了qwq
#include<cmath> #include<queue> #include<cstdio> #include<iostream> #include<algorithm> #define rg register #ifdef _WIN32 #define lld "I64d" #else #define lld "%lld" #endif using namespace std; inline long long read(){ long long a=0; int f=0; char c=getchar(); while(c<'0'||c>'9') { f|=c=='-'; c=getchar(); } while(c>='0'&&c<='9') { a=(a<<3)+(a<<1)+(c^48); c=getchar(); } return f? -a:a; } int t,n,m,fir[2002],dis[2002],cnt,q[6000006],head,tail,num[2002]; bool vis[2002],flag; struct edge{int v,w,nxt;} e[6006]; void add(int x,int y,int z){ e[++cnt].v=y,e[cnt].w=z,e[cnt].nxt=fir[x],fir[x]=cnt; } bool spfa(){ while(head<tail){ int u=q[++head]; vis[u]=0; if(num[u]>n) return 1; for(int i=fir[u],v;v=e[i].v,i;i=e[i].nxt){ if(dis[v]>dis[u]+e[i].w){ dis[v]=dis[u]+e[i].w,num[v]=num[u]+1; if(num[v]>n) return 1; if(!vis[v]) vis[v]=1,q[++tail]=v; } } } return 0; } int main(){ // freopen("testdata.in","r",stdin); // freopen("qaq.txt","w",stdout); t=read(); while(t--){ n=read(),m=read(); for(int i=1;i<=n;++i) dis[i]=214748364,q[i]=0,vis[i]=0,fir[i]=0; cnt=0,q[1]=1,head=0,tail=1,num[1]=vis[1]=1,dis[1]=0; for(int i=1,x,y,z;i<=m;++i){ x=read(),y=read(),z=read(),add(x,y,z); if(z>=0) add(y,x,z); } if(spfa()) printf("YE5\n"); else printf("N0\n"); } return 0; }