Data Structures19 sections · 729 units
Open in Course

Evaluate Division: Weighted UF

Ratios as weights

Map variable names to indices. For equation a/b=va/b = v:

  • Union aa and bb with weight vv

To query a/ca/c:

  • Find roots of both
  • If different roots, return 1-1
  • If same root, return weight[a]/weight[c]\text{weight}[a] / \text{weight}[c]
def find(x):
    if parent[x] != x:
        originalParent = parent[x]
        parent[x] = find(parent[x])
        weight[x] *= weight[originalParent]
    return parent[x]

def union(a, b, val):
    rootA, rootB = find(a), find(b)
    if rootA == rootB:
        return
    # rootA/rootB = weight[b] * val / weight[a]
    parent[rootA] = rootB
    weight[rootA] = weight[b] * val / weight[a]

The weight calculation during union ensures consistency.