var
n,m,t,l,x,y,z :longint;
i :longint;
flag :boolean;
last,dis :array[0..200010] of longint;
vis :array[0..200010] of boolean;
pre,other,len :array[0..400010] of longint;
procedure connect(x,y,z:longint);
begin
inc(l);
pre[l]:=last[x];
last[x]:=l;
other[l]:=y;
len[l]:=z;
end;
procedure dfs(x:longint);
var
p,q:longint;
begin
if flag then exit;
vis[x]:=true;
q:=last[x];
while (q<>0) do
begin
p:=other[q];
if flag then exit;
if (dis[p]>dis[x]+len[q]) then
begin
dis[p]:=dis[x]+len[q];
if vis[p] then
begin
flag:=true;exit;
end else dfs(p);
end;
q:=pre[q];
end;
vis[x]:=false;
end;
begin
read(t);
while (t>0) do
begin
dec(t);
fillchar(vis,sizeof(vis),false);l:=0;flag:=false;
fillchar(last,sizeof(last),0);
fillchar(dis,sizeof(dis),0);
read(n,m);
for i:=1 to m do
begin
read(x,y,z);
if (z<0) then connect(x,y,z) else
begin
connect(x,y,z);
connect(y,x,z);
end;
end;
for i:=1 to n do
begin
dfs(i);
if flag then break;
end;
if flag then writeln('YE5') else writeln('N0');
end;
end.
——by Eirlys
判断负环 dfs-spfa 模板【pascal】
最新推荐文章于 2023-02-10 19:43:53 发布