洛谷P1551親戚(java,并查集)-創(chuàng)新互聯(lián)

若某個家族人員過于龐大,要判斷兩個是否是親戚,確實(shí)還很不容易,現(xiàn)在給出某個親戚關(guān)系圖,求任意給出的兩個人是否具有親戚關(guān)系。

易縣網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,易縣網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為易縣1000+提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的易縣做網(wǎng)站的公司定做!

附圖(洛谷)

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

3bb9f5dad4e248afa693dd0de065f0fd.png

代碼實(shí)現(xiàn):

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);
    }
}

你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧

名稱欄目:洛谷P1551親戚(java,并查集)-創(chuàng)新互聯(lián)
URL標(biāo)題:http://muchs.cn/article14/dsiode.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設(shè)計公司、Google、外貿(mào)建站標(biāo)簽優(yōu)化、企業(yè)網(wǎng)站制作企業(yè)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司