Map variable names to indices. For equation :
- Union and with weight
To query :
- Find roots of both
- If different roots, return
- If same root, return
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
# weight[a] * val = weight[b] after union
# So rootA's weight relative to rootB is weight[b] / (weight[a] * val)
parent[rootA] = rootB
weight[rootA] = weight[b] / (weight[a] * val)
The weight calculation during union ensures consistency.