[英]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.