不懂为什么MLE

P3367 【模板】并查集

321zdq @ 2016-09-24 21:59:58

var
f:array[1..10000]of integer;
n,x,y,z:integer;m:longint;

function find(x:integer):integer;
begin
if f[x]=0 then exit(x);
if f[f[x]]=0 then exit(f[x]);
find:=find(f[x]);
f[x]:=find;
end;

begin
read(n,m);
fillchar(f,n,0);
while m>0 do
begin
read(z,x,y);
case z of
1:f[find(y)]:=find(x);
2:if find(x)=find(y) then writeln('Y') else writeln('N');
end;
dec(m);
end;
end.

by 321zdq @ 2016-09-24 22:07:00

改了一下,还是MLE

var
f:array[1..10000]of longint;
m,n,x,y,z:longint;

function find(x:longint):longint;
begin
if f[x]=0 then exit(x);
if f[f[x]]=0 then exit(f[x]);
find:=find(f[x]);
f[x]:=find;
end;

begin
read(n,m);
fillchar(f,n,0);
while m>0 do
begin
read(z,x,y);
case z of
1:f[find(y)]:=find(x);
2:if find(x)=find(y) then writeln('Y') else writeln('N');
end;
dec(m);
end;
end.

by _rqy @ 2016-10-05 10:26:36

合并时没有判断x,y是否在同一个并查集内,导致某节点的父节点是自己,结果无限递归,栈溢出


by interestingLSY @ 2016-10-25 21:35:08

楼上说得对


|