class UnionFind {
constructor (n) {
this.count = n;
this.id = {};
for (let i = 0; i < n; i++) {
this.id[i] = i;
}
}
find (a) {
while (a !== this.id[a]) {
const parentA = this.id[a];
this.id[a] = this.id[parentA];
a = this.id[a];
}
return a;
}
union (a, b) {
const rootA = this.find(a);
const rootB = this.find(b);
if (rootA === rootB) return;
this.id[rootA] = rootB;
this.count--;
}
}