Advertisement
hoangreal

Union Find Class

Oct 21st, 2024
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. class UnionFind:
  2.     """
  3.    Union-Find (Disjoint Set Union) class to group elements into clusters.
  4.    
  5.    Time Complexity: O(α(n)), where α is the Inverse Ackermann function, very slow-growing.
  6.    Space Complexity: O(n), where n is the number of elements.
  7.    """
  8.  
  9.     def __init__(self):
  10.         self.parent = {}
  11.         self.rank = {}
  12.  
  13.     def find(self, item):
  14.         """Find the root representative of the item."""
  15.         if self.parent[item] != item:
  16.             self.parent[item] = self.find(self.parent[item])  # Path compression
  17.         return self.parent[item]
  18.  
  19.     def union(self, item1, item2):
  20.         """Union the sets that contain item1 and item2."""
  21.         root1 = self.find(item1)
  22.         root2 = self.find(item2)
  23.         if root1 != root2:
  24.             # Union by rank
  25.             if self.rank[root1] > self.rank[root2]:
  26.                 self.parent[root2] = root1
  27.             elif self.rank[root1] < self.rank[root2]:
  28.                 self.parent[root1] = root2
  29.             else:
  30.                 self.parent[root2] = root1
  31.                 self.rank[root1] += 1
  32.  
  33.     def add(self, item):
  34.         """Add an item to the union-find structure."""
  35.         if item not in self.parent:
  36.             self.parent[item] = item
  37.             self.rank[item] = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement