Skip to content

Commit 2c00c4c

Browse files
authored
bruih
1 parent c4cff97 commit 2c00c4c

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

solutions/gold/cf-468B.mdx

+18-18
Original file line numberDiff line numberDiff line change
@@ -31,27 +31,27 @@ We can treat each set as a graph with several connected components. For each $p_
3131
#include <bits/stdc++.h>
3232
using namespace std;
3333

34+
// BeginCodeSnip{Disjoint Set Union}
3435
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;
5352
}
5453
};
54+
// EndCodeSnip
5555

5656
int main() {
5757
int n, a, b;

0 commit comments

Comments
 (0)