[LintCode] Connecting Graph II
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 }
以上是关于[LintCode] Connecting Graph II的主要内容,如果未能解决你的问题,请参考以下文章
[LintCode] Connecting Graph II
MySQL 5.6主从Slave_IO_Running:Connecting/error connecting to master *- retry
从 Connecting 到 NotConnected 的 Multipeer Connectivity 会话
为啥 JS WebSocket 在 sparkjava 中会卡在 CONNECTING 上?