Skip to content

Commit ed5adce

Browse files
authored
pp
1 parent 09fc523 commit ed5adce

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

solutions/gold/cf-468B.mdx

+21-14
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,30 @@ We can treat each set as a graph with several connected components. For each $p_
3535
using namespace std;
3636

3737
// 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+
}
4447

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+
}
4652

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; }
4858

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;
5562
return true;
5663
}
5764
};

0 commit comments

Comments
 (0)