[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 }