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:
connect(a, b)
, an edge to connect node a and node bquery()
, 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();
}
}