Connecting Graph III

Given n nodes in a graph labeled from 1 to n. There is no edges in the graph at beginning.

You need to support the following method:

  1. connect(a, b), an edge to connect node a and node b
  2. query(), Returns the number of connected component in the graph

Example

Example 1:

Input:
ConnectingGraph3(5)
query()
connect(1, 2)
query()
connect(2, 4)
query()
connect(1, 4)
query()

Output:[5,4,3,3]

Example 2:

Input:
ConnectingGraph3(6)
query()
query()
query()
query()
query()


Output:
[6,6,6,6,6]

思路:connect的时候,decrease count就可以了,一开始是n,连接一次,少一个;

public class ConnectingGraph3 {
    private class UnionFind {
        private int[] father;
        private int count;
        public UnionFind(int n) {
            this.father = new int[n + 1];
            for(int i = 0; i <= n; i++) {
                father[i] = i;
            }
            this.count = n;
        }

        public int find(int x) {
            int j = x;
            while(father[j] != j) {
                j = father[j];
            }
            // path compression;
            while(x != j) {
                int fx = father[x];
                father[x] = j;
                x = fx;
            }
            return j;
        }

        public void union(int a, int b) {
            int root_a = find(a);
            int root_b = find(b);
            if(root_a != root_b) {
                father[root_a] = root_b;
                this.count--;
            }
        }

        public int getCount() {
            return this.count;
        }
    }

    /**
     * @param a: An integer
     * @param b: An integer
     * @return: nothing
     */
    private UnionFind uf;
    public ConnectingGraph3(int n) {
        uf = new UnionFind(n);
    }
    
    public void connect(int a, int b) {
       uf.union(a, b);
    }

    /**
     * @return: An integer
     */
    public int query() {
        return uf.getCount();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值