若某個(gè)家族人員過于龐大,要判斷兩個(gè)是否是親戚,確實(shí)還很不容易,現(xiàn)在給出某個(gè)親戚關(guān)系圖,求任意給出的兩個(gè)人是否具有親戚關(guān)系。
附圖(洛谷)
鏈接:https://www.luogu.com.cn/problem/P1551
代碼實(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級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧
名稱欄目:洛谷P1551親戚(java,并查集)-創(chuàng)新互聯(lián)
URL標(biāo)題:http://jinyejixie.com/article14/dsiode.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁(yè)設(shè)計(jì)公司、Google、外貿(mào)建站、標(biāo)簽優(yōu)化、企業(yè)網(wǎng)站制作、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容