class UnionFind: def __init__(self, n): self.count = n self.p = [i for i in range(n)] def parent(self, i): root = i while self.p[root] != root: root = self.p[root] while self.p[i] != i: x = i i = self.p[i] self.p[x] = root return root def union(self, i, j): p1 = self.parent(self.p, i) p2 = self.parent(self.p, j) self.p[p1] = p2