洛谷P1551亲戚(java,并查集)-创新互联

若某个家族人员过于庞大,要判断两个是否是亲戚,确实还很不容易,现在给出某个亲戚关系图,求任意给出的两个人是否具有亲戚关系。

易县网站建设公司创新互联公司,易县网站设计制作,有大型网站制作公司丰富经验。已为易县1000+提供企业网站建设服务。企业网站搭建\成都外贸网站制作要多少钱,请找那个售后服务好的易县做网站的公司定做!

附图(洛谷)

链接:https://www.luogu.com.cn/problem/P1551

3bb9f5dad4e248afa693dd0de065f0fd.png

代码实现:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int p = sc.nextInt();
        
        UnionFind unionFind = new UnionFind(n);
        for (int i = 0; i< m; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            unionFind.union(x, y);
        }
        for (int i = 0; i< p; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            boolean flag = unionFind.isSameSet(x, y);
            if (flag) {
                System.out.println("Yes");
            } else {
                System.out.println("No");
            }
        }
    }
}

class UnionFind {
        HashMapfather;
        
        public UnionFind (int n) {
            father = new HashMap<>();
            for (int i = 1; i<= n; i++) {
                father.put(i, null);
            }
        }
    
    public int findFather (int x) {
        int root = x;
        //找祖先
        while (father.get(root) != null) {
            root = father.get(root);
        }
        //压缩路径
        while (x != root) {
            int original_father = father.get(x);
            father.put(x,root);
            x = original_father;
            
        }
        return root;
    }
    //合并
    public void union(int x, int y) {
        int rootX = findFather(x);
        int rootY = findFather(y);
        
        if (rootX != rootY) {
            father.put(rootX, rootY);
        }
    }
    
    public boolean isSameSet(int x, int y) {
        return findFather(x) == findFather(y);
    }
}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


文章标题:洛谷P1551亲戚(java,并查集)-创新互联
分享地址:http://pwwzsj.com/article/dsiode.html