Week 1: Union-Find读书笔记[Tree Union Find]

实现segwick所说的Union quick find 按照数组保存每个数组中保存该集合的父节点index, 判断是否连接的时候复杂度为O(lgn)最差n, 但是合并集合的复杂度为O(lgn)最差n

 

public class QuickFindTree {
    private int [] collection;
    private int count;
    private int unitcount;
    /**
     * 使用树形 来构造集合体系 
     * 是否连接操作  复杂度期望为lgn 实际最坏为n
     * union也是一样复杂度期望为lgn 实际最坏为n
     */
    
    QuickFindTree(int count) {
        Init(count);
    }
    
    void Init(int count) {
        this.count = count;
        this.unitcount = count;
        collection = new int[count];
        for(int i = 0; i < count; i++) {
            collection[i] = i;
        }
    }
    
    int top(int a) {
        while(a != collection[a]) {
            a = collection[a];
        }
        return a;
    }
    
    boolean isConnected(int a, int b) {
        return ( top(a) == top(b) );
    }
    
    void union(int a, int b) {
        int atop = top(a);
        int btop = top(b);
        collection[btop] = atop;
        this.unitcount--;
    }
    
    int GetUnitCount() {
        return this.unitcount;
    }
    
    public static void main(String[] args) {
        int N = StdIn.readInt();
        System.out.println(N);
        QuickFindTree uf = new QuickFindTree(N);
        long sTime=System.currentTimeMillis();
        while (!StdIn.isEmpty())
        {
            int p = StdIn.readInt();
            int q = StdIn.readInt();
            
            if (!uf.isConnected(p, q))
            {
                uf.union(p, q);
            }
        }
        long eTime=System.currentTimeMillis();
        System.out.println("[CostTime] : "+(eTime-sTime) + "ms"+ " [Unit Count] : " + uf.GetUnitCount());
        
    }

}

分别用小数据 中数据 大数据测试结果如下:

大数据还是出不来  需要优化代码

posted @ 2014-02-21 15:14  CodePUB  阅读(79)  评论(0)    收藏  举报