首页 > 代码库 > luoguP1551 亲戚
luoguP1551 亲戚
P1551 亲戚
题目背景
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
题目描述
规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。
输入输出格式
输入格式:
第一行:三个整数n,m,p,(n<=5000,m<=5000,p<=5000),分别表示有n个人,m个亲戚关系,询问p对亲戚关系。
以下m行:每行两个数Mi,Mj,1<=Mi,Mj<=N,表示Ai和Bi具有亲戚关系。
接下来p行:每行两个数Pi,Pj,询问Pi和Pj是否具有亲戚关系。
输出格式:
P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。
输入输出样例
输入样例#1:
6 5 31 21 53 45 21 31 42 35 6
输出样例#1:
YesYesNo
说明
非常简单的并查集入门题哦!!!
最初版本:
1 program relation; 2 const 3 inf=‘relation.in‘; 4 outf=‘relation.out‘; 5 var 6 father:array[0..20000] of longint; 7 i,n,m,q,a,b,t1,t2:longint; 8 9 function find(apple:longint):longint;10 begin11 if father[apple]<>apple then father[apple]:=find(father[apple]);12 exit(father[apple]);13 end;14 15 procedure union(aa,bb:longint);16 begin17 father[bb]:=aa;18 end;19 20 21 begin22 //assign(input,inf);23 //assign(output,outf);24 //reset(input); rewrite(output);25 26 readln(n,m,q);27 for i:= 1 to n do28 father[i]:=i; //init;29 30 for i:= 1 to m do31 begin32 read(a,b);33 t1:=find(a);34 t2:=find(b);35 if t1<>t2 then union(t1,t2);36 end;37 38 for i:= 1 to q do //ask39 begin40 readln(a,b);41 if find(a)=find(b) then writeln(‘Yes‘)42 else writeln(‘No‘);43 end;44 45 close(input);46 close(output);47 end.
优化版本:
1 { 2 并查集: 3 先读入,然后找两个点的flag,然后合并(后面接着前面) 4 } 5 6 program relation; 7 const 8 inf=‘relation.in‘; 9 outf=‘relation.out‘;10 var11 father:array[0..20000] of longint;12 i,n,m,q,a,b,t1,t2:longint;13 14 function find(apple:longint):longint;15 begin16 if father[apple]<>apple then father[apple]:=find(father[apple]);17 exit(father[apple]);18 end;19 20 procedure union(aa,bb:longint);21 begin22 father[bb]:=aa;23 end;24 25 begin26 //assign(input,inf);27 //assign(output,outf);28 //reset(input); rewrite(output);29 30 readln(n,m,q);31 for i:= 1 to n do32 father[i]:=i; //init;33 34 for i:= 1 to m do35 begin36 read(a,b);37 t1:=find(a);38 t2:=find(b);39 if t1<>t2 then union(t1,t2);40 end;41 42 for i:= 1 to q do //ask43 begin44 readln(a,b);45 if find(a)=find(b) then writeln(‘Yes‘)46 else writeln(‘No‘);47 end;48 49 close(input);50 close(output);51 end.
luoguP1551 亲戚
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。