题目描述:
若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易。 现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。 我们规定:如果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个询问的答案为“具有”或“不具有”亲戚关系。
import java.util.Scanner;
public class relationship {
static int[] f;
public relationship(int a){
f = new int[a];
for(int i = 0; i < a; i++) {
f[i] = i+1;
}
}
public int getRelationship(int x) {
return f[x-1] == x?x:getRelationship(f[x-1]);
}
public void merge(int a,int b) {
int left = getRelationship(a);
int right = getRelationship(b);
if (left != right) {
f[right] = left;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int allPerson = in.nextInt();
int allRelationship = in.nextInt();
int allCheck = in.nextInt();
String[] answer = new String[allCheck];
relationship rs = new relationship(allPerson);
int left = 0;
int right = 0;
for(int i = 0; i < allRelationship; i++) {
left = in.nextInt();
right = in.nextInt();
rs.merge(left,right);
}
int l = 0;
int r = 0;
for(int i = 0; i < allCheck; i++) {
left = in.nextInt();
right = in.nextInt();
l = rs.getRelationship(left);
r = rs.getRelationship(right);
answer[i] = (l == r?"yes":"no");
}
for(int i = 0; i < answer.length; i++) {
System.out.println(answer[i]);
}
}
}
运行示例:
如有不足之处,请大家批评指正,谢谢!