- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 50 lines of Python from the credited upstream file 3108.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind:2 def __init__(self, n: int):3 self.id = list(range(n))4 self.rank = [0] * n5 6 self.weight = [(1 << 17) - 1] * n7 8 def unionByRank(self, u: int, v: int, w: int) -> None:9 i = self._find(u)10 j = self._find(v)11 newWeight = self.weight[i] & self.weight[j] & w12 self.weight[i] = newWeight13 self.weight[j] = newWeight14 if i == j:15 return16 if self.rank[i] < self.rank[j]:17 self.id[i] = j18 elif self.rank[i] > self.rank[j]:19 self.id[j] = i20 else:21 self.id[i] = j22 self.rank[j] += 123 24 def getMinCost(self, u: int, v: int) -> int:25 if u == v:26 return 027 i = self._find(u)28 j = self._find(v)29 return self.weight[i] if i == j else -130 31 def _find(self, u: int) -> int:32 if self.id[u] != u:33 self.id[u] = self._find(self.id[u])34 return self.id[u]35 36 37class Solution:38 def minimumCost(39 self,40 n: int,41 edges: list[list[int]],42 query: list[list[int]],43 ) -> list[int]:44 uf = UnionFind(n)45 46 for u, v, w in edges:47 uf.unionByRank(u, v, w)48 49 return [uf.getMinCost(u, v) for u, v in query]50