家族

Description

若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。

Input

第一行:三个整数n,m,p,(n<=50000,m<=50000,p<=50000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有亲戚关系。接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。

Output

P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。

Sample Input

6 5 3
41 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6

Sample Output

Yes
Yes
No

程序:

var
n,m,k:longint;
r,p:array[0..60000]of longint;                              w=

function find(x:longint):longint;
var
y,w,root:longint;
begin
    y:=x;
    while p[y]>0 do y:=p[y];
    root:=y;
    y:=x;
    while p[y]>0 do
    begin
        w:=p[y];p[y]:=root;y:=w;
    end;
    find:=root;
end;

procedure union(x,y:longint);
var
u,v:longint;
begin
    u:=find(x);
    v:=find(y);
    if r[u]<=r[v] then
    begin
        p[u]:=v;
        if r[u]=r[v] then r[v]:=r[v]+1;
    end else
    p[v]:=u;
end;

procedure init;
var
i,x,y:longint;
begin
    readln(n,m,k);
    for i:=1 to m do
    begin
        readln(x,y);
        if find(x)<>find(y) then union(x,y);
    end;
end;

procedure main;
var
i,x,y:longint;
begin
    for i:=1 to k do
    begin
        readln(x,y);
        if find(x)=find(y) then writeln('Yes') else writeln('No');
    end;
end;

begin
    init;
    main;
end.

原文地址:https://www.cnblogs.com/YYC-0304/p/9500023.html