Commit ed5adce 1 parent 09fc523 commit ed5adce Copy full SHA for ed5adce
File tree 1 file changed +21
-14
lines changed
1 file changed +21
-14
lines changed Original file line number Diff line number Diff line change @@ -35,23 +35,30 @@ We can treat each set as a graph with several connected components. For each $p_
35
35
using namespace std ;
36
36
37
37
// BeginCodeSnip{DSU}
38
- struct DSU {
39
- vector < int > e ;
40
- DSU (int N ) { e = vector <int >(N , - 1 ); }
41
-
42
- // get representive component (uses path compression)
43
- int get (int x ) { return e[x ] < 0 ? x : e [x ] = get (e [x ]); }
38
+ class DisjointSets {
39
+ private :
40
+ vector < int > parents ;
41
+ vector < int > sizes ;
42
+
43
+ public :
44
+ DisjointSets (int size ) : parents (size ), sizes (size , 1 ) {
45
+ for (int i = 0 ; i < size ; i ++) { parents [i ] = i ; }
46
+ }
44
47
45
- bool same_set (int a , int b ) { return get(a ) == get(b ); }
48
+ /** @return the "representative" node in x's component */
49
+ int get (int x ) {
50
+ return parents[x ] == x ? x : (parents [x ] = get (parents [x ]));
51
+ }
46
52
47
- int size (int x ) { return -e [get (x )]; }
53
+ /** @return whether the merge changed connectivity */
54
+ bool unite (int x , int y ) {
55
+ int x_root = find (x );
56
+ int y_root = find (y );
57
+ if (x_root == y_root ) { return false ; }
48
58
49
- bool unite (int x , int y ) { // union by size
50
- x = get (x ), y = get (y );
51
- if (x == y ) return false;
52
- if (e [x ] > e [y ]) swap(x , y );
53
- e [x ] += e [y ];
54
- e [y ] = x ;
59
+ if (sizes [x_root ] < sizes [y_root ]) { swap (x_root , y_root ); }
60
+ sizes[x_root ] += sizes[y_root ];
61
+ parents[y_root ] = x_root;
55
62
return true;
56
63
}
57
64
};
You can’t perform that action at this time.
0 commit comments