zoukankan      html  css  js  c++  java
  • 加权路径压缩并查集实现

    package algs4;
    
    import edu.princeton.cs.algs4.StdIn;
    import edu.princeton.cs.algs4.StdOut;
    
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    /**
     * 并查集
     * Created by blank on 2015-10-15 下午8:56.
     */
    public class UF {
    
        public static void main(String[] args) throws Exception {
            InputStream input = new FileInputStream(Constants.PATH + "largeUF.txt");
            System.setIn(input);
            int N = StdIn.readInt();
            UF uf = new UF(N);
            while (N-- > 0) {
                int p = StdIn.readInt();
                int q = StdIn.readInt();
                if (uf.connected(p, q)) continue;
                uf.union(p, q);
    //            StdOut.println(p + " " + q);
            }
            StdOut.println(uf.getCount() + " components");
    
        }
    
        private int[] parent;
        private byte[] rank;
        private int count;
    
        public UF(int n) {
            count = n;
            parent = new int[n];
            rank = new byte[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                rank[i] = 0;
            }
        }
    
        public int getCount() {
            return count;
        }
    
        public boolean connected(int p, int q) {
            return find(p) == find(q);
        }
    
        private int find(int p) {
            while (p != parent[p]) {
                parent[p] = parent[parent[p]];
                p = parent[p];
            }
            return p;
        }
    
        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP == rootQ) {
                return;
            }
            if (rank[rootP] < rank[rootQ]) {
                parent[rootP] = rootQ;
            } else if (rank[rootP] > rank[rootQ]) {
                parent[rootQ] = rootP;
            } else {
                parent[rootP] = rootQ;
                rank[rootQ]++;
            }
            count--;
        }
    
    }
  • 相关阅读:
    百度地图API示例之小实践 添加代理商标注
    MySQL分组操作
    MySQL连表操作
    MySQL多对多操作
    MySQL一对一操作
    MySQL唯一索引
    MySQL用户授权管理
    MySQL外键操作
    MySQL删操作
    MySQL增操作
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4884496.html
Copyright © 2011-2022 走看看