[英]Path Compression , How does this code is path compression?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package algorithm1;
/**
*
* @author Navin
*/
public class QuickUnionWeighted {
private int [] id;
private int [] size;
int numberOfChild;
int j=0;
public QuickUnionWeighted(int N){
id = new int[N];
size = new int[N];
for(int i=0;i<N;i++){
id[i] = i;
size[i]=1;
}
}
public int root(int i){
while (i != id[i]){
id[i] = id[id[i]];
i=id[i];
}
return i;
}
public boolean connected(int p,int q){
return(root(p) == root(q));
}
public void union(int p,int q){
int i = root(p);
int j = root(q);
// if(i == j) return;
if(size[i] < size[j]){
id[i] = j;
size[j] += size[i];
}else{
id[j] = i;
size[i] +=size[j];
}
for(int k=0;k<size.length;k++){
System.out.print(size[k]+" ");
}
}
public static void main(String [] args){
QuickUnionWeighted quw = new QuickUnionWeighted(10);
quw.union(3,0);
quw.union(4, 0);
quw.union(3, 5);
quw.union(3, 6);
quw.union(3,9);
}
}
因為當我檢查代碼時, id[i] = id[id[i]]
指向節點的父節點,並且檢查的節點沒有移動到它的祖父節點,樹也沒有展平。
請指導。
id[i] = id[id[i]];
這一行是路徑壓縮。 id[i]
是節點i
的父節點。 因此,這條線將節點i
重新鏈接到它的祖父節點。 因此,它跳過了父級。 然后,祖父母等也會發生同樣的情況。 這會使樹變平。
這是這一步的可視化:
1 1
^ / \
| root(3) / \
2 --------> 2 3
^
|
3
我知道這是遲到的。 但萬一有人仍然需要這個。
正如 Nico 所說,這一行是路徑壓縮:
id[i] = id[id[i]];
但它所做的是將節點i
直接連接到它的祖父節點。 然后它跳過父節點,並且從祖父節點開始重復整個過程。 從而壓平樹。
但是,為了將節點i
直接連接到根節點,這里是路徑壓縮的另一種實現:
id[i] = root(id[i]);
這將創建一個遞歸函數,該函數向下到根節點,並將該路徑上的每個節點設置為直接指向根節點。
檢查https://algorithms.tutorialhorizon.com/disjoint-set-union-find-algorithm-union-by-rank-and-path-compression/和本材料的第 9 頁https://cseweb.ucsd.edu/classes /sp15/cse100-ab/lectures/Lec17_pdf.pdf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.