Skip to content

Instantly share code, notes, and snippets.

@rcabreu
Last active June 7, 2023 19:50
Show Gist options
  • Save rcabreu/6241630 to your computer and use it in GitHub Desktop.
Save rcabreu/6241630 to your computer and use it in GitHub Desktop.
C++::data_structures::UnionFind
class UnionFind {
private:
vector<int> p;
vector<int> rank;
public:
UnionFind(int n) {
rank.assign(n, 0);
p.resize(n);
for (int i = 0; i < n; ++i) p[i] = i;
}
int findSet(int i) {
return p[i] == i ? i : p[i] = findSet(p[i]);
}
bool isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
void join(int i, int j) {
if (isSameSet(i, j)) return;
int u = findSet(i), v = findSet(j);
if (rank[u] > rank[v]) p[v] = u;
else {
p[u] = v;
if (rank[u] == rank[v]) ++rank[v];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment