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
# rootA/rootB = weight[b] * val / weight[a]
parent[rootA] = rootB
weight[rootA] = weight[b] * val / weight[a]
The weight calculation during union ensures consistency.