[LintCode] Connecting Graph III

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] 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
5 // n = 5
query() return 5
connect(1, 2)
query() return 4
connect(2, 4)
query() return 3
connect(1, 4)
query() return 3


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

 

 

以上是关于[LintCode] Connecting Graph III的主要内容,如果未能解决你的问题,请参考以下文章

[LintCode] Connecting Graph II

MySQL 5.6主从Slave_IO_Running:Connecting/error connecting to master *- retry

从 Connecting 到 NotConnected 的 Multipeer Connectivity 会话

为啥 JS WebSocket 在 sparkjava 中会卡在 CONNECTING 上?

MySQL主从:slave status显示connecting状态解决方法

主从同步出现一下错误:Slave_IO_Running: Connecting