1. package com.example.suanfa.alg1;
    2. /**并查集使用
    3. * @author lfy
    4. * @date 2022-05-28
    5. */
    6. public class BingChaCollection {
    7. int[] fa,rank;
    8. public void init(int n){
    9. for (int i = 0; i < n; i++) {
    10. fa[i] = i;
    11. rank[i] = 1;
    12. }
    13. }
    14. public int find(int x){
    15. if (fa[x] == x){
    16. return x;
    17. }else {
    18. return find(fa[x]);
    19. }
    20. //return fa[x] == x ? x : find(fa[x]);
    21. }
    22. //树根据秩(节点的子树深度)进行合并,浅子树合并到深子树
    23. public void merge(int i, int j)
    24. {
    25. int x = find(i), y = find(j);
    26. if (rank[x] <= rank[y]){
    27. fa[x] = y;}
    28. else{
    29. fa[y] = x;}
    30. if (rank[x] == rank[y] && x != y){
    31. rank[y]++;}
    32. }
    33. //亲戚问题,两个人的根节点只要在一个集合中,就说明有亲戚问题
    34. public static void main(String[] args) {
    35. //分别表示有n个人,m个亲戚关系,询问p对亲戚关系。
    36. int n=0, m=0, p=0, x=0, y=0;
    37. BingChaCollection test = new BingChaCollection();
    38. test.init(n);
    39. for (int i = 0; i < m; ++i)
    40. {
    41. //scanf("%d%d", &x, &y);
    42. test.merge(x, y);
    43. }
    44. for (int i = 0; i < p; ++i)
    45. {
    46. //scanf("%d%d", &x, &y);
    47. System.out.println(test.find(x) == test.find(y) ? "Yes" : "No");
    48. }
    49. }
    50. }