并查集系列(二)——Union-find with specific canonical element

问题描述

Union-find with specific canonical element. Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union(), connected(), and find() should all take logarithmic time or better. For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components.

思路分析

通过添加一个数组来完成对于每个树最大值进行维护

JAVA代码实现

public class FindMax {
    private  int[] max = new int[10]; // 每个节点对应树的最大值
    private  int[] roots = new int[10]; // 每个点的父节点
    private  int[] points = new int[10]; // 每个点所在树的节点数量

    public FindMax(){
        for (int i = 0; i < roots.length; i++) {
            roots[i] = i;
        }
        for (int i = 0; i < points.length; i++) {
            points[i] = 1;
        }
        for (int i = 0; i < max.length; i++) {
            max[i] = i;
        }
    }

    public  int find(int a){
        return max[root(a)];
    }

    public  void union(int a, int b) {
        int rootA = root(a);
        int rootB = root(b);
        if (root(rootA) != root(rootB)) {
            if (points[rootA] < points[rootB]) {
                roots[rootA] = rootB;
                points[rootB] += points[rootA];
                if(max[rootA]> max[rootB]) max[rootB] = max[rootA];
            }
            if (points[rootB] <= points[rootA]) {
                roots[rootB] = rootA;
                points[rootA] += points[rootB];
                if(max[rootB]> max[rootA]) max[rootA] = max[rootB];
            }
        }
    }

    public  int root(int a) {
        while (roots[a] != a) {
            a = roots[a];
        }
        return a;
    }

    public static void main(String[] args) {
        FindMax find = new FindMax();
        find.union(1, 2);
        find.union(1, 4);
        find.union(4, 6);
        find.union(5, 2);
        System.out.println(find.find(2));
    }

}

运行结果:

6

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值