家族 SSL_1896 (并查集)

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
 a:array[0..50001] of longint;
 ans:array[0..50001] of boolean;
 i,n,m,j,k,x,y,tot,max,sort1,sort2:longint;

procedure find(x,y:longint);
 var
 i:longint;
begin
 if a[x]<>0 then find(a[x],y+1)
            else begin
                 if tot=0 then tot:=y;
                 exit;
                 end;
end;

function root(x,y:longint):longint;
begin
 if a[x]<>0 then root:=root(a[x],y);
   if max=0 then
    begin
      if x=y then max:=y
             else max:=x;
    end;
   exit;
end;

procedure union(x,y:longint);
 var
 u,v,i:longint;
begin
 tot:=0;
 find(x,1);
 u:=tot;
 tot:=0;
 find(y,1);
 v:=tot;
 if u>v then begin
             max:=0;
             root(y,y);
             a[max]:=x;
             end
        else begin
             max:=0;
             root(x,x);
             a[max]:=y;
             end;
end;

begin
 readln(n,m,k);
 fillchar(a,sizeof(a),0);
 for i:=1 to m do
  begin
   readln(x,y);
   max:=0;
   root(x,x);
   sort1:=max;
   max:=0;
   root(y,y);
   sort2:=max;
   if sort1=0 then union(x,y)
    else if (sort1<>sort2) then union(x,y);
  end;
 for i:=1 to m do
  if a[i]<>0 then
  begin
  max:=0;
  root(i,i);
  a[i]:=max;
  end;
 for i:=1 to k do
  begin
   readln(x,y);
   max:=0;
   root(x,x);
   sort1:=max;
   max:=0;
   root(y,y);
   sort2:=max;
   if sort1<>sort2 then ans[i]:=false
                   else ans[i]:=true;
  end;
 for i:=1 to k do
  if ans[i]=true then writeln('Yes')
                 else writeln('No');

end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值