- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 61 lines of Python from the credited upstream file maximize-spanning-tree-stability-with-upgrades.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 UnionFind(object): 6 def __init__(self, n):7 self.set = range(n)8 self.rank = [0]*n9 10 def find_set(self, x):11 stk = []12 while self.set[x] != x: 13 stk.append(x)14 x = self.set[x]15 while stk:16 self.set[stk.pop()] = x17 return x18 19 def union_set(self, x, y):20 x, y = self.find_set(x), self.find_set(y)21 if x == y:22 return False23 if self.rank[x] > self.rank[y]: 24 x, y = y, x25 self.set[x] = self.set[y]26 if self.rank[x] == self.rank[y]:27 self.rank[y] += 128 return True29 30 31class Solution(object):32 def maxStability(self, n, edges, k):33 """34 :type n: int35 :type edges: List[List[int]]36 :type k: int37 :rtype: int38 """39 uf = UnionFind(n)40 cnt = 041 result = float("inf")42 for u, v, s, m in edges:43 if not m:44 continue45 if not uf.union_set(u, v):46 return -147 cnt += 148 result = min(result, s)49 edges.sort(key=lambda x: -x[2])50 for u, v, s, m in edges:51 if m:52 continue53 if not uf.union_set(u, v):54 continue55 cnt += 156 if cnt == (n-1)-k:57 result = min(result, s)58 elif cnt == n-1:59 result = min(result, 2*s)60 return result if cnt == n-1 else -161