描述 Description
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。
规定:x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。如果x,y是亲戚,那么x的亲戚都是y的亲戚,y的亲戚也都是x的亲戚。
输入格式 Input Format
第一行:三个整数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是否具有亲戚关系。
输出格式 Output Format
P行,每行一个’Yes’或’No’。表示第i个询问的答案为“具有”或“不具有”亲戚关系。
样例输入 Sample Input
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
样例输出 Sample Output
时间限制 Time Limitation
Yes
Yes
No
各点1S
来源 Source
cdwind整理提交
分析:典型的并查集问题,也是最为简单的并查集问题,读入时进行unit处理,将同根点的点指向同一个父亲,寻找时只寻找父亲结点比较即可。
代码:
program p1251; var father:array[1..5000]of integer; n,m,p,t1,t2:longint; function getfather(m:integer):longint; begin if father[m]<>m then father[m]:=getfather(father[m]); exit(father[m]); end; procedure unition(x,y:longint); var p,q,i:longint; begin p:=getfather(x); q:=getfather(y); for i:=1 to n do if father[i]=q then father[i]:=p; end; procedure init; var i,j,k,x,y:integer; begin // assign(input,'input.txt'); // reset(input); // assign(output,'output.txt'); // rewrite(output); read(n,m,p); for i:=1 to n do father[i]:=i; for i:=1 to m do begin readln(x,y); unition(x,y); end; for i:=1 to p do begin readln(x,y); t1:=getfather(x); t2:=getfather(y); if t1=t2 then writeln('Yes') else writeln('No'); end; // close(input); // close(output); end; begin init; end.
浙公网安备 33010602011771号