• Java实现weightedUF


    实现需要以下两点:

    1.跟踪树的大小(树的元素个数)。

    2.将小树链接到大树上。

    代码来自红书:算法(第4版),很简洁。

    import java.util.NoSuchElementException;
    
    public class WeightedQuickUnionUF {
        private int[] sz; //size of set
        private int[] id; //parent node;
        int count; 
        
        public WeightedQuickUnionUF(int N) {
            count = N;
            id = new int[N];
            for(int i = 0; i < N; i++) {
                id[i] = i;
            }
            sz = new int[N];
            for(int i = 0; i < N; i++) sz[i] = 1;
        }
        
        public int  count() {
            return count;
        }
        
        public boolean connected(int p, int q) {
            return find(p) == find(q);
        }
    
        public int find(int p) {
            while(p != id[p]) p = id[p];
            return p;
        }
        
        public void union(int p, int q) {
            int i = find(p);
            int j = find(q);
            if(i == j) return;
            if(sz[i] < sz[j]) {
                id[i] = id[j];
                sz[j] += sz[i];
            } else {
                id[j] = id[i];
                sz[i] += sz[j];
            }
            count--;
        }
    }
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    上采样和下采样
    二、决策树算法
    一、实现贝叶斯算法
    Centos7 安装vscode
    Centos安装IDEA
    Centos设置自带中文输入法
    Centos 安装mysql
    Centos,tomcat
    Centos 7 安装JDK
    Centos7 安装rar,unrar,zip,unzip
  • 原文地址:https://www.cnblogs.com/Shinered/p/10703251.html
Copyright © 2020-2023  润新知