union-find算法——使用路径压缩的加权quick-union算法实现

上篇文章union-find算法的使用路径压缩的加权quick-union算法实现

路径压缩就是说在find函数中将所查询触点到根触点所在路径上的所有触点直接连接到根触点上

性能为常数级别

package demo;



public class PathCompressWQU {


/**
* @param args
*/
private int count;
private int[] id;
private int[] sz;

public PathCompressWQU(int n){
count = n;
id = new int[n];
sz = new int[n];
for(int i = 0; i < n; i++){
id[i] = i;
sz[i] =  1;
}
}

public int find(int p){
int temp = p;
while(p != id[p]){
p = id[p];
}

while(temp != id[p]){
int tempId = id[temp];
id[temp] = id[p];
temp = tempId;
}

return id[p];
}

public boolean connect(int p, int q){
return find(p) == find(q);
}

public void union(int p, int q){
int pRoot = find(p);
int qRoot = find(q);

if(pRoot == qRoot) return;

if(sz[pRoot] < sz[qRoot]){
id[pRoot] = id[qRoot];
sz[qRoot] += sz[pRoot];
}
else{
id[qRoot] = id[pRoot];
sz[pRoot] += sz[qRoot];
}

count--;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

int n = StdIn.readInt();


PathCompressWQU pcwqu = new PathCompressWQU(n);
while(!StdIn.isEmpty()){
int p = StdIn.readInt();
int q = StdIn.readInt();

if(pcwqu.connect(p, q)) continue;

pcwqu.union(p, q);

StdOut.println(p + " " + q);
  }

StdOut.println(pcwqu.count + "components");
}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值