并查集笔记

概念

并查集是一种树型的数据结构,用于处理一些不相交集合(DisjointSets)(Disjoint Sets)的合并及查询问题。

代码

Var father:array[0..100000] of longint;
    i,n,m,k,a,b:longint;

function get_father(m:longint):longint;
Begin
        if father[m]=m then exit(m)
        else
        Begin
                father[m]:=get_father(father[m]);
                exit(father[m]);
        end;
end;

function together(a,b:longint):boolean;
Begin
        a:=get_father(a);b:=get_father(b);
        father[a]:=b;
end;

procedure do_it;
Var i:longint;
Begin
        readln(n,m);
        for i:=1 to n do
        Begin
                father[i]:=i;
        end;

        for i:=1 to m do
        Begin
                readln(a,b);
                together(a,b);
        end;

        readln(k);
        for i:=1 to k do
        Begin
                readln(a,b);
                if get_father(a)=get_father(b) then
                Begin
                        writeln('Yes');
                end
                else
                Begin
                        writeln('No');
                end;
        end;
end;

Begin 
        do_it;
end.
posted @ 2019-07-13 15:55  willbe233  阅读(31)  评论(0)    收藏  举报