[LintCode] Connecting Graph II

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(a), Returns the number of connected component nodes which include node a.

 

Example
5 // n = 5
query(1) return 1
connect(1, 2)
query(1) return 2
connect(2, 4)
query(1) return 3
connect(1, 4)
query(1) return 3



 1 class UnionFind {
 2     private int[] father = null;
 3     private int[] numsInUnion = null;
 4     
 5     public UnionFind(int n){
 6         father = new int[n];
 7         numsInUnion = new int[n];
 8         for(int i = 0; i < n; i++){
 9             father[i] = i;
10             numsInUnion[i] = 1;
11         }
12     }
13     public int find(int x){
14         if(father[x] == x){
15             return x;
16         }
17         return father[x] = find(father[x]);
18     }
19     public void connect(int a, int b){
20         int root_a = find(a);
21         int root_b = find(b);
22         if(root_a != root_b){
23             father[root_a] = root_b;
24             numsInUnion[root_b] += numsInUnion[root_a];
25         }
26     }
27     public int queryNumInUnion(int a){
28         return numsInUnion[find(a)];
29     }
30 }
31 public class ConnectingGraph2 {
32     private UnionFind uf = null;
33     public ConnectingGraph2(int n) {
34         uf = new UnionFind(n);
35     }
36 
37     public void connect(int a, int b) {
38         uf.connect(a - 1, b - 1);
39     }
40         
41     public int query(int a) {
42         return uf.queryNumInUnion(a - 1);
43     }
44 }


转载于:https://www.cnblogs.com/lz87/p/7500090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值