File tree 1 file changed +18
-18
lines changed
1 file changed +18
-18
lines changed Original file line number Diff line number Diff line change @@ -31,27 +31,27 @@ We can treat each set as a graph with several connected components. For each $p_
31
31
#include < bits/stdc++.h>
32
32
using namespace std ;
33
33
34
+ // BeginCodeSnip{Disjoint Set Union}
34
35
struct DSU {
35
- vector < int > p , sz ;
36
- DSU (int n ) {
37
- p.resize(n);
38
- sz.resize(n , 1 );
39
- iota(p.begin(), p.end(), 0 );
40
- }
41
- int get (int x ) {
42
- if (p [x ] != x ) { p [x ] = get (p [x ]); }
43
- return p[x ];
44
- }
45
- void unite(int a, int b) {
46
- a = get(a);
47
- b = get(b);
48
- if (sz[a ] < sz [b ]) { swap(a , b ); }
49
- if (a != b ) {
50
- p [b ] = a ;
51
- sz [a ] += sz [b ];
52
- }
36
+ vector < int > e ;
37
+ DSU (int N ) { e = vector <int >(N , - 1 ); }
38
+
39
+ // get representive component (uses path compression)
40
+ int get (int x ) { return e[x ] < 0 ? x : e [x ] = get (e [x ]); }
41
+
42
+ bool same_set (int a , int b ) { return get(a ) == get(b ); }
43
+
44
+ int size (int x ) { return -e [get (x )]; }
45
+
46
+ bool unite (int x , int y ) { // union by size
47
+ x = get (x ), y = get (y );
48
+ if (x == y ) return false;
49
+ if (e [x ] > e [y ]) swap(x , y );
50
+ e [x ] += e [y ]; e [y ] = x ;
51
+ return true;
53
52
}
54
53
};
54
+ // EndCodeSnip
55
55
56
56
int main () {
57
57
int n, a, b;
You can’t perform that action at this time.
0 commit comments