Skip to content

Latest commit

 

History

History
53 lines (40 loc) · 2.07 KB

union_find.md

File metadata and controls

53 lines (40 loc) · 2.07 KB

Union Find

  • Union Find (or disjoint-set) is a very elegant data structure
  • Essentially it utilizes a list representation for the joint data points
    • the index of the data point indicates its linkage status
  • For detailed explanation, please see this Lecture Notes

Template

class UnionFind:
    def __init__(self, n):
        self.count = n
        self.parent = list(range(n))  # root list
        self.size = [1] * n  # weight
        
    def find(self, i):
        while self.parent[i] != i:
            self.parent[i] = self.parent[self.parent[i]]  # Path compression
            i = self.parent[i]
        return i
    
    def union(self, p, q):
        i, j = self.find(p), self.find(q)
        
        if i == j:
            return 

        # merge smaller tree into larger tree to obtain a flat structure
        if self.size[i] < self.size[j]:
            self.parent[i] = j
            self.size[j] += self.size[i]
        else:
            self.parent[j] = i
            self.size[i] += self.size[j]
        
        self.count -= 1

Reference:

Practice: