Last active
June 7, 2023 19:50
-
-
Save rcabreu/6241630 to your computer and use it in GitHub Desktop.
C++::data_structures::UnionFind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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