并查集(DSU)中两种提高算法效率的方法:path compression && union-by-rank.

1.path compression

If a node we are visiting is not a root node of a tree, then we modify the structure of the tree to make sure this node and all of its ancestor nodes(except the root node) share the root node as their common parent node. Just like the illustration shows:
在这里插入图片描述

public int find(int x) {
	if(x != parent[x]) {
   		parent[x] = find(parent[x]);
   	}
    return parent[x];
}
2.union-by-rank

Here the rank just means the height of a tree.
Each time we invoke the function union(int x, int y), we will firstly find two root nodes xr and yr. If xr is not equal to yr, then we will do the union.
We always comply to the following principle:
Let the node having the higher rank be the parent node of the other node, if the two nodes have the same rank, we randomly choose one node to be the parent node of the other, and the rank of the node which becomes the parent node increases by 1.

public boolean union(int x, int y) {
    int xr = find(x);
    int yr = find(y);
    if(xr == yr) {
        return false;
    }else{
        if(rank[xr] < rank[yr]) {
            parent[xr] = yr; 
        }else if(rank[xr] > rank[yr]) {
            parent[yr] = xr;
        }else{
            parent[yr] = xr;
            rank[xr]++;
        }
        return true;
    }
}
3.The complete DSU code:
class DSU {
    private int[] parent;
    private int[] rank;
    
    public DSU(int N) {
        parent = new int[N];
        rank = new int[N];
        
        for(int i = 0; i < N; i++) {
            parent[i] = i;
        }
    }
    
    public int find(int x) {
        if(x != parent[x]) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
    
    public boolean union(int x, int y) {
        int xr = find(x);
        int yr = find(y);
        if(xr == yr) {
            return false;
        }else{
            if(rank[xr] < rank[yr]) {
                parent[xr] = yr; 
            }else if(rank[xr] > rank[yr]) {
                parent[yr] = xr;
            }else{
                parent[yr] = xr;
                rank[xr]++;
            }
            return true;
        }
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值