Sub topic 2
Warm-up: Subtree Sizes and Sums
This chapter assumes you know array DP, adjacency lists, and DFS. It also assumes you can root a tree and walk its pre-order in reverse, so that every child is finished before its parent. Each problem below uses that same loop. Only the state each node stores changes.
Subtree Sizes and Sums
A subtree aggregate is a value that a node collects from its children. Subtree size works like this: every node starts at 1, and each finished child adds its size to its parent. A subtree sum of weights works the same way, with weight[u] as the starting value instead of 1. Each edge is used once, so the pass runs in O(n).
Take It or Leave It: Independent Set and Vertex Cover
An independent set is a set of nodes with no two of them adjacent. One number per node is not enough here, because the parent needs to know whether the child was chosen. So each node keeps two states:
take[u]is the best total in u's subtree with u chosen. Every child must then be skipped.skip[u]is the best total with u not chosen. Each child is free to be either state, so the parent adds the better one.
A minimum vertex cover uses the mirror rule. If u is out of the cover, every child must be in it. If u is in, each child takes its cheaper state. The complement of any vertex cover is an independent set, so the minimum cover weight also equals the total weight minus the maximum independent set.
Paths That Bend: Diameter and Maximum Path Sum
A longest path climbs up to some highest node and then goes back down. At that node it joins the node's two deepest child branches. Store down[u], the longest downward path from u. Before you update a parent's down with a new branch, combine that branch with the best branch the parent has seen so far.
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent, seen, order, stack = [-1] * n, [False] * n, [], [root]
seen[root] = True
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
def max_weight_independent_set(n, edges, weight, root=0):
parent, order, _ = root_tree(n, edges, root)
take, skip = list(weight), [0] * n
for u in reversed(order):
p = parent[u]
if p != -1:
take[p] += skip[u]
skip[p] += max(take[u], skip[u])
return max(take[root], skip[root])
def tree_diameter(n, edges):
parent, order, _ = root_tree(n, edges, 0)
down, best = [0] * n, 0
for u in reversed(order):
p = parent[u]
if p != -1:
cand = down[u] + 1
best = max(best, down[p] + cand)
down[p] = max(down[p], cand)
return best
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
print(root_tree(5, edges)[2]) # [5, 3, 1, 1, 1]
print(max_weight_independent_set(5, edges, [1, 5, 1, 1, 1])) # 6
print(tree_diameter(5, edges)) # 3For a maximum path sum with node weights, the start of down[u] changes to weight[u]. Each branch becomes max(0, down[child]), which drops branches with a negative sum. The best path through u is then weight[u] plus its two best branches.
Exercise
Write the transitions for minimum-weight vertex cover using states in[u] and out[u].
Show answer
in[u] = weight[u] + sum over children c of min(in[c], out[c]); out[u] = sum over children c of in[c]. The answer is min(in[root], out[root]).