【Lintcode】591. Connecting Graph III

題目地址:

https://www.lintcode.com/problem/connecting-graph-iii/description

給定nn個頂點標號爲1n1\sim n,再給定若干次操作,每次操作會將兩個頂點用無向邊連起來。要求動態返回連通分量個數。

並查集天然適合這個問題。代碼如下:

public class ConnectingGraph3 {
    
    class UnionFind {
        private int[] parent, rank;
        // group記錄有多少個等價類
        int group;
        
        public UnionFind(int n) {
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                rank[i] = 1;
            }
            
            group = n;
        }
        
        public int find(int p) {
            if (p != parent[p]) {
                parent[p] = find(parent[p]);
            }
            
            return parent[p];
        }
        
        public void union(int p, int q) {
            int pRoot = find(p), qRoot = find(q);
            if (pRoot == qRoot) {
                return;
            }
            
            if (rank[pRoot] < rank[qRoot]) {
                parent[pRoot] = qRoot;
            } else if (rank[pRoot] > rank[qRoot]) {
                parent[qRoot] = pRoot;
            } else {
                parent[pRoot] = qRoot;
                rank[qRoot]++;
            }
            
            group--;
        }
    }
    
    private UnionFind uf;
    
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: nothing
     */
    public ConnectingGraph3(int n) {
        // initialize your data structure here.
        uf = new UnionFind(n);
    }
    
    public void connect(int a, int b) {
        // write your code here
        uf.union(a - 1, b - 1);
    }
    
    /**
     * @return: An integer
     */
    public int query() {
        // write your code here
        return uf.group;
    }
}

時間複雜度O(klogk)O(k\log^*k)kk是查詢次數),空間O(n)O(n)nn爲頂點個數)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章