Skip to content

Instantly share code, notes, and snippets.

@ddoronin
Created October 28, 2021 17:09
Show Gist options
  • Save ddoronin/4b194e384e587f9fc14c43009e87beb9 to your computer and use it in GitHub Desktop.
Save ddoronin/4b194e384e587f9fc14c43009e87beb9 to your computer and use it in GitHub Desktop.
class DSU {
private p: number[];
constructor(n: number) {
this.p = new Array(n).fill(0).map((_, i) => i);
}
find(x: number) {
while(this.p[x] !== x) {
x = this.p[x];
}
return x;
}
union(x: number, y: number) {
this.p[this.find(x)] = this.find(y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment