dfs_SPFA 判负环
感觉有点像tarjan求SCC
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
const int MAXN=400005;
int init(){
int rv=0,fh=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-') fh=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
rv=(rv<<1)+(rv<<3)+c-'0';
c=getchar();
}
return fh*rv;
}
struct edge{
int to,nxt,dis;
}e[MAXN];
int nume,n,m,head[MAXN],T,dis[MAXN];
bool f[MAXN];
void adde(int from,int to,int dis){
e[++nume].to=to;
e[nume].dis=dis;
e[nume].nxt=head[from];
head[from]=nume;
}
bool dfs_SPFA(int u){
f[u]=1;
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(dis[v]>dis[u]+e[i].dis){
if(f[v]) return 1;
dis[v]=dis[u]+e[i].dis;
if(dfs_SPFA(v)) return 1;
}
}
f[u]=0;
return 0;
}
int main(){
freopen("in.txt","r",stdin);
T=init();
while(T--){
bool isis=0;
memset(head,0,sizeof(head));
memset(f,0,sizeof(f));
memset(dis,0,sizeof(dis));
nume=0;
n=init();m=init();
for(int i=1;i<=m;i++){
int u=init(),v=init(),di=init();
adde(u,v,di);
if(di>=0) adde(v,u,di);
}
for(int i=1;i<=n;i++){
if(dfs_SPFA(i)){printf("YE5\n");isis=1;break;}
}
if(!isis) printf("N0\n");
}
fclose(stdin);
return 0;
}