洛谷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://lszwz.com/article/dsiode.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款