MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / DSU

Class DSU

MinimizeHammingDistance/MinimizeHammingDistance.cpp:7–26  ·  view source on GitHub ↗

============================ Disjoint Set Union (Union-Find) ============================

Source from the content-addressed store, hash-verified

5// Disjoint Set Union (Union-Find)
6// ============================
7class DSU {
8public:
9 vector<int> parent, rank;
10 DSU(int n) {
11 parent.resize(n);
12 rank.resize(n, 0);
13 for (int i = 0; i < n; i++) parent[i] = i;
14 }
15 int find(int x) {
16 if (parent[x] != x) parent[x] = find(parent[x]);
17 return parent[x];
18 }
19 void unite(int x, int y) {
20 int rx = find(x), ry = find(y);
21 if (rx == ry) return;
22 if (rank[rx] < rank[ry]) parent[rx] = ry;
23 else if (rank[ry] < rank[rx]) parent[ry] = rx;
24 else parent[ry] = rx, rank[rx]++;
25 }
26};
27
28// ============================
29// Solution Class

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected