bawang51吧 关注:31贴子:3,169
  • 5回复贴,共1

【OI】并查集

只看楼主收藏回复

var a:array[1..100]of longint;
n,m,p,i,x,y,xx,yy:longint;
begin
readln(n,p);
for i:=1 to p do
a[i]:=i;
for i:=1 to n do
begin
readln(x,y);
a[x]:=a[y];
end;
readln(m);
for i:=1 to m do
begin
readln(x,y);
xx:=x;
while a[xx]<>xx do
xx:=a[xx];
a[x]:=xx;
yy:=y;
while a[yy]<>yy do
yy:=a[yy];
a[y]:=a[yy];
if a[x]=a[y] then
writeln('YES')
else
writeln('NO');
end;
end.


IP属地:上海1楼2011-08-11 19:08回复
    路径压缩版:var a:array[1..100]of longint;
    n,m,p,i,x,y,xx,yy:longint;
    begin
    readln(n,p);
    for i:=1 to p do
    a[i]:=i;
    for i:=1 to n do
    begin
    readln(x,y);
    a[x]:=a[y];
    end;
    readln(m);
    for i:=1 to m do
    begin
    readln(x,y);
    xx:=x;
    while a[xx]<>xx do
    begin
    a[xx]:=a[a[xx]];
    xx:=a[xx];
    end;
    a[x]:=xx;
    yy:=y;
    while a[yy]<>yy do
    begin
    a[yy]:=a[a[yy]];
    yy:=a[yy];
    end;
    a[y]:=yy;
    if a[y]=a[x] then
    writeln('yes')
    else
    writeln('no');
    end;
    end.


    IP属地:上海2楼2011-08-16 11:05
    回复
      楼上版本除了路径压缩以外,还可以越级查询,能防**,为最快速非递归版!!!


      IP属地:上海3楼2011-08-16 11:13
      回复
        竟然被和*了?
        就是我是你爸而且你是我爸。


        IP属地:上海4楼2011-08-16 11:14
        回复
          楼上全是错的
          这个才是对的
          var a:array[1..1000]of longint;
          i,r,m,n,x,y:longint;
          function father(o:longint):longint;
          begin
          if a[o]<>o then
          a[o]:=father(a[o]);
          exit(a[o]);
          end;
          begin
          readln(r,m,n);
          for i:=1 to r do
          a[i]:=i;
          for i:=1 to m do
          begin
          readln(x,y);
          a[father(x)]:=a[y];
          end;
          for i:=1 to n do
          begin
          readln(x,y);
          if father(x)=father(y) then
          writeln('Y')
          else
          writeln('N');
          end;
          end.


          IP属地:上海5楼2011-10-18 20:51
          回复
            最快的
            var a:array[1..1000]of longint;
            i,r,m,n,x,y:longint;
            function father(o:longint):longint;
            begin
            if a[o]<>o then
            a[o]:=father(a[o]);
            exit(a[o]);
            end;
            begin
            readln(r,m,n);
            for i:=1 to r do
            a[i]:=i;
            for i:=1 to m do
            begin
            readln(x,y);
            a[father(x)]:=father(y);
            end;
            for i:=1 to n do
            begin
            readln(x,y);
            if father(x)=father(y) then
            writeln('Y')
            else
            writeln('N');
            end;
            end.


            IP属地:上海6楼2011-10-18 20:56
            回复