【数据结构】之并查集(树的实现方法)

1,概念

并查集是一种很不一样的树形结构
需要解决的问题是什么?
连接问题

  • 网络中节点连接的状态(网络是个抽象的概念,用户之间形成的网络)
  • 数学中集合类的实现
    连接问题和路径问题
    连接问题比路径问题回答的问题要少

2,图解

思路:将每一颗树,看做是一个节点

  1. 开始的时候,每个节点都没有连接起来,自己指向自己
    在这里插入图片描述

  2. 把4指向3
    在这里插入图片描述

  3. 把3指向8
    在这里插入图片描述

  4. 把6和5指在一起
    在这里插入图片描述

  5. 把9和4指在一起
    在这里插入图片描述

  6. 把6和二指在一起
    在这里插入图片描述
    在这里插入图片描述

3,代码实现(java版本)

public class UnionFind2 {

    // 我们的第二版Union-Find, 使用一个数组构建一棵指向父节点的树
    // parent[i]表示第一个元素所指向的父节点
    private int[] parent;
    private int count;  // 数据个数

    // 构造函数
    public UnionFind2(int count){
        parent = new int[count];
        this.count = count;
        // 初始化, 每一个parent[i]指向自己, 表示每一个元素自己自成一个集合
        for( int i = 0 ; i < count ; i ++ )
            parent[i] = i;
    }

    // 查找过程, 查找元素p所对应的集合编号
    // O(h)复杂度, h为树的高度
    private int find(int p){
        assert( p >= 0 && p < count );
        // 不断去查询自己的父亲节点, 直到到达根节点
        // 根节点的特点: parent[p] == p
        while( p != parent[p] )
            p = parent[p];
        return p;
    }

    // 查看元素p和元素q是否所属一个集合
    // O(h)复杂度, h为树的高度
    public boolean isConnected( int p , int q ){
        return find(p) == find(q);
    }

    // 合并元素p和元素q所属的集合
    // O(h)复杂度, h为树的高度
    public void unionElements(int p, int q){

        int pRoot = find(p);
        int qRoot = find(q);

        if( pRoot == qRoot )
            return;

        parent[pRoot] = qRoot;
    }
}

4,改进

通过以上的代码,我们实现了基本的并查集,但是效率并不高,主要原因是在unionElements的时候,
parent[pRoot] = qRoot;
的顺序不确定,导致树可能高,因此效率慢,这里我们引入一个size数组,
private int[] sz; // sz[i]表示以i为根的集合中元素个数
在构造函数里:sz[i] = 1;
在unionElement中,修改添加代码

// 根据两个元素所在树的元素个数不同判断合并方向
        // 将元素个数少的集合合并到元素个数多的集合上
        if( sz[pRoot] < sz[qRoot] ){
            parent[pRoot] = qRoot;
            sz[qRoot] += sz[pRoot];
        }
        else{
            parent[qRoot] = pRoot;
            sz[pRoot] += sz[qRoot];
        }

人生有酒须尽欢。

猜你喜欢

转载自blog.csdn.net/qq_41346335/article/details/87785530
今日推荐