Sub topic 12
Extension: Storing Relative Weights Between Elements
This chapter assumes you can write the DisjointSet class with union by size and path compression, and that you understand amortized cost. It shows how to store a numeric difference on each parent link so the structure can answer "how far apart are these two elements?"
The problem
Plain union-find only says whether two elements are in the same set. Some problems also give relations such as "B is 5 more than A" or "A weighs twice as much as B". You must then answer queries about elements that were never compared directly, and detect a new fact that contradicts the old ones.
The idea is to give each node a number, diff[x], equal to value(x) - value(parent[x]). The true values are never stored. Only differences along parent links are.
Find with weights
A node's difference to the root is the sum of the diff values along its path. Path compression is the natural place to compute it. While re-pointing each node at the root, we replace its diff with its total difference to the root.
The path is walked from the node nearest the root outward. Each node adds its old diff to a running total, which already holds the difference from its parent to the root.
Union with weights
Say union(a, b, w) records value(b) = value(a) + w. After both finds, diff[a] and diff[b] are differences to the roots ra and rb. Linking rb under ra needs value(rb) - value(ra), which equals w + diff[a] - diff[b]. If union by size attaches the roots the other way around, negate that number.
If a and b already share a root, the new fact is either redundant or a contradiction. Compare diff[b] - diff[a] with w.
class WeightedDisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.diff = [0] * n # diff[x] = value(x) - value(parent[x])
def find(self, x):
path = []
node = x
while self.parent[node] != node:
path.append(node)
node = self.parent[node]
root = node
total = 0
for node in reversed(path): # nearest the root first
total += self.diff[node]
self.diff[node] = total # now relative to the root
self.parent[node] = root
return root
def union(self, a, b, w):
"""Record value(b) = value(a) + w. Return False on a contradiction."""
ra, rb = self.find(a), self.find(b)
if ra == rb:
return self.diff[b] - self.diff[a] == w
d = w + self.diff[a] - self.diff[b] # value(rb) - value(ra)
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
d = -d
self.parent[rb] = ra
self.diff[rb] = d
self.size[ra] += self.size[rb]
return True
def difference(self, a, b):
"""Return value(b) - value(a), or None if the elements are unrelated."""
if self.find(a) != self.find(b):
return None
return self.diff[b] - self.diff[a]
ds = WeightedDisjointSet(4)
ds.union(0, 1, 5)
ds.union(1, 2, 3)
print(ds.difference(0, 2)) # 8
print(ds.difference(0, 3)) # None
print(ds.union(0, 2, 7)) # False, because the known difference is 8
ds.union(3, 2, -1) # value(2) = value(3) - 1, and the roots swap
print(ds.difference(0, 3)) # 9
print(ds.difference(1, 3)) # 4Common errors
- Reading
diffbeforefind.diff[x]is relative to the root only right afterfind(x). Before that it is relative to the parent. - Wrong sign after a swap. When union by size reverses which root becomes the child, the stored difference must be negated, as the
d = -dline does. - Forgetting the same-root case. Skipping the consistency check makes contradictory input pass silently.
- Recursive find in Python. A long chain can exceed the recursion limit, so this version uses loops.
Exercise
After union(0, 1, 5) and union(2, 1, 4), which means value(1) = value(2) + 4, what does difference(0, 2) return?
Show answer
1. The first call gives value(1) = value(0) + 5. The second gives value(2) = value(1) - 4 = value(0) + 1. So value(2) - value(0) = 1.