forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDisjointUnionSet.java
More file actions
86 lines (79 loc) · 2.31 KB
/
DisjointUnionSet.java
File metadata and controls
86 lines (79 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Disjoint Set Union (Union-Find) data structure with path compression
* and union by size optimizations.
*
* Time Complexity: O(α(n)) amortized for both find and union operations,
* where α(n) is the inverse Ackermann function (effectively constant).
* Space Complexity: O(n) for parent and size arrays.
*/
class DSU {
private int[] parent;
private int[] size;
/**
* Initializes the DSU with n elements, each in its own set.
*
* @param n the number of elements (0 to n-1)
*/
public DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
/**
* Finds the representative (root) of the set containing x.
* Implements path compression by making all nodes on the path
* point directly to the root.
*
* @param x the element whose set representative to find
* @return the root of the set containing x
*/
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
/**
* Unites the sets containing x and y.
* Uses union by size: attaches smaller tree under root of larger tree.
*
* @param x first element
* @param y second element
* @return true if sets were merged, false if already in same set
*/
public boolean union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) return false;
if (size[rootX] < size[rootY]) {
parent[rootX] = rootY;
size[rootY] += size[rootX];
} else {
parent[rootY] = rootX;
size[rootX] += size[rootY];
}
return true;
}
/**
* Checks if two elements belong to the same set.
*
* @param x first element
* @param y second element
* @return true if x and y are in the same set, false otherwise
*/
public boolean connected(int x, int y) {
return find(x) == find(y);
}
/**
* Returns the size of the set containing x.
*
* @param x the element whose set size to retrieve
* @return the number of elements in the set containing x
*/
public int getSize(int x) {
return size[find(x)];
}
}