@@ -23,6 +23,7 @@ void Union_ineff(int parent[], int x, int y)
23
23
struct subset
24
24
{
25
25
int parent, rank;
26
+ subset () = default ;
26
27
subset (int parent, int rank) :
27
28
parent (parent),
28
29
rank (rank)
@@ -31,30 +32,34 @@ struct subset
31
32
}
32
33
};
33
34
34
- int find (subset subsets[], int i)
35
- {
36
- // Path compression
37
- if (subsets[i].parent != i)
38
- subsets[i].parent = find (subsets, subsets[i].parent );
39
-
40
- return subsets[i].parent ;
41
- }
42
-
43
- int Union (subset subsets[], int x, int y)
44
- {
45
- int xRoot = find (subsets, x);
46
- int yRoot = find (subsets, y);
47
-
48
- // Attach smaller rank tree under higher rank tree root
49
- if (subsets[xRoot].rank < subsets[yRoot].rank )
50
- subsets[xRoot].parent = yRoot;
51
- if (subsets[yRoot].rank < subsets[xRoot].rank )
52
- subsets[yRoot].parent = xRoot;
53
-
54
- // If same rank, make one as root and increment the rank.
55
- else
56
- {
57
- subsets[yRoot].parent = xRoot;
58
- subsets[xRoot].rank ++;
59
- }
60
- }
35
+ int find (struct subset subsets[], int i)
36
+ {
37
+ // find root and make root as parent of i (path compression)
38
+ if (subsets[i].parent != i)
39
+ subsets[i].parent = find (subsets, subsets[i].parent );
40
+
41
+ return subsets[i].parent ;
42
+ }
43
+
44
+ // A function that does union of two sets of x and y
45
+ // (uses union by rank)
46
+ void Union (struct subset subsets[], int x, int y)
47
+ {
48
+ int xroot = find (subsets, x);
49
+ int yroot = find (subsets, y);
50
+
51
+ // Attach smaller rank tree under root of high rank tree
52
+ // (Union by Rank)
53
+ if (subsets[xroot].rank < subsets[yroot].rank )
54
+ subsets[xroot].parent = yroot;
55
+ else if (subsets[xroot].rank > subsets[yroot].rank )
56
+ subsets[yroot].parent = xroot;
57
+
58
+ // If ranks are same, then make one as root and increment
59
+ // its rank by one
60
+ else
61
+ {
62
+ subsets[yroot].parent = xroot;
63
+ subsets[xroot].rank ++;
64
+ }
65
+ }
0 commit comments