public class WeightedQuickUnion {
int[] parent; // parent[i] = parent of i
int[] size; // size[i] = number of sites in subtree rooted at i
int count; // number of components
/**
* Initializes an empty union–find data structure
* Each site is initially in its own
* component.
* n is the number of sites
*/
public WeightedQuickUnion(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
/**
* Return the number of components.
*
*/
public int count() {
return count;
}
/**
* return the component identifier for the component containing p.
* p the integer representing the item
*/
public int find(int p) {
validate(p);
while (p != parent[p])
p = parent[p];
return p;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* return true if the the item p and item q are in the same component.
*/
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merge the component containing p with the
* the component containing q.
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public class WeightedQuickUnion {
int[] parent; // parent[i] = parent of i
int[] size; // size[i] = number of sites in subtree rooted at i
int count; // number of components
/**
* Initializes an empty union–find data structure
* Each site is initially in its own
* component.
* n is the number of sites
*/
public WeightedQuickUnion(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
/**
* Return the number of components.
*
*/
public int count() {
return count;
}
/**
* return the component identifier for the component containing p.
* p the integer representing the item
*/
public int find(int p) {
validate(p);
while (p != parent[p])
p = parent[p];
return p;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n - 1));
}
}
/**
* return true if the the item p and item q are in the same component.
*/
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merge the component containing p with the
* the component containing q.
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
} else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}