- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 45 lines of Python from the credited upstream file incremental-even-weighted-cycle-queries.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.
123 45class Solution(object):6 def numberOfEdgesAdded(self, n, edges):7 """8 :type n: int9 :type edges: List[List[int]]10 :rtype: int11 """12 class UnionFind(object): 13 def __init__(self, n):14 self.set = range(n)15 self.rank = [0]*n16 self.parity = [0]*n 17 18 def find_set(self, x):19 stk = []20 while self.set[x] != x: 21 stk.append(x)22 x = self.set[x]23 prev = self.parity[x] 24 while stk:25 self.parity[stk[-1]] ^= prev 26 prev = self.parity[stk[-1]] 27 self.set[stk.pop()] = x28 return x29 30 def union_set(self, x, y, w):31 x0, y0 = x, y32 x, y = self.find_set(x), self.find_set(y)33 if x == y:34 return self.parity[x0]^w^self.parity[y0] == 0 35 if self.rank[x] > self.rank[y]: 36 x, y = y, x37 elif self.rank[x] == self.rank[y]:38 self.rank[y] += 139 self.set[x] = self.set[y]40 self.parity[x] = self.parity[x0]^w^self.parity[y0] 41 return True42 43 uf = UnionFind(n)44 return sum(uf.union_set(u, v, w) for u, v, w in edges)45