Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Created February 3, 2020 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriybuday/9fa907eaaba8431ae633af57ecc2e66c to your computer and use it in GitHub Desktop.
Save andriybuday/9fa907eaaba8431ae633af57ecc2e66c to your computer and use it in GitHub Desktop.
DisjointSetUnion
class DisjointSetUnion {
int[] parent;
public DisjointSetUnion(int n) {
parent = new int[n];
for(int i = 0; i < n; ++i) {
parent[i] = i;
}
}
public int find(int x) {
if(parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int x, int y) {
parent[find(x)] = find(y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment