Sub topic 9
Tree Knapsack: Merging Child Tables
This chapter assumes you know 0/1 knapsack on arrays and the root_tree helper from earlier chapters. root_tree returns parent, a pre-order order, and subtree sizes. In every DP so far, each node stored a fixed number of values. Tree knapsack is different. Each node stores a whole table indexed by "how many nodes I use," and the main step is merging a child's table into its parent's.
The problem
You are given a tree with a value on every node and a budget k. You want the largest total value of a connected set of exactly k nodes that contains the root. Connectivity is what makes this a tree problem. You can only include a node if its parent is also included.
The state is:
dp[u][j]is the best total value of a connected set ofjnodes that containsuand lies insideu's subtree. If no such set exists, the entry is-inf.
The base case is a node alone: dp[u] = [-inf, value[u]]. Index 0 is impossible because the set must contain u.
The merge step
Say the parent p has already absorbed some of its children, so table a covers p plus those children. Now child u arrives with a finished table b. For each subtree there are two choices:
- Skip
u's subtree entirely. The parent's existing entriesa[i]stay as they are. - Take
j ≥ 1nodes fromu's side, which must includeu. Combined withinodes on the parent side, this givesi + jnodes wortha[i] + b[j].
This is the same as 0/1 knapsack, where each child is an item whose cost can be any j.
The code
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 = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
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
NEG = float('-inf')
def best_rooted_subtree(n, edges, value, k, root=0):
# dp[u][j]: max total value of a connected set of j nodes
# that contains u and lies inside u's subtree (k >= 1)
parent, order, _ = root_tree(n, edges, root)
dp = [[NEG, value[u]] for u in range(n)]
for u in reversed(order):
p = parent[u]
if p == -1:
continue
a, b = dp[p], dp[u]
merged = list(a) + [NEG] * (min(len(a) + len(b) - 1, k + 1) - len(a))
for i in range(1, len(a)):
if a[i] == NEG:
continue
for j in range(1, len(b)):
if i + j > k:
break
if a[i] + b[j] > merged[i + j]:
merged[i + j] = a[i] + b[j]
dp[p] = merged
dp[u] = None
r = dp[root]
return r[k] if k < len(r) else None
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
print(best_rooted_subtree(5, edges, [1, 2, 3, 4, 5], 3)) # 8Reversed pre-order guarantees that when u is merged into p, all of u's own children have already been merged into dp[u], so b is final. Starting merged as a copy of a covers the "skip this child" choice.
Tracing the example
| Step | Table | Contents (index 0..) |
|---|---|---|
| leaves 3, 4 | `dp[3]`, `dp[4]` | `[-inf, 4]`, `[-inf, 5]` |
| 1 absorbs 4 | `dp[1]` | `[-inf, 2, 7]` |
| 1 absorbs 3 | `dp[1]` | `[-inf, 2, 7, 11]` |
| 0 absorbs 2 | `dp[0]` | `[-inf, 1, 4]` |
| 0 absorbs 1 | `dp[0]` | `[-inf, 1, 4, 8]` |
The answer dp[0][3] = 8 comes from the set {0, 1, 4}.
Common errors
- Allocating full-length tables. If every table has length
k + 1from the start and both loops run tok, each merge costs O(k²) and the total is O(n·k²). The table length has to track the real subtree size, capped atk + 1. - Forgetting the cap. Without the
min(..., k + 1), tables grow up to the subtree size, and the bound degrades to O(n²) even whenkis small. - Recursive DFS on deep trees. A path of 10⁵ nodes overflows Python's recursion limit. The iterative order used here avoids that.
- Holding every table in memory. Setting
dp[u] = Noneafter the merge releases child tables you no longer need.
Size-bounded tables give O(n·k) total work. That bound is not obvious, and the next chapter proves it.
Exercise
Change the function so it returns the best connected set of exactly k nodes anywhere in the tree, not only sets that contain the root. What do you change?
Show answer
Every connected set has a unique topmost node u, and that set is counted in dp[u][k]. Before freeing dp[u], check whether len(dp[u]) > k and update a running maximum with dp[u][k]. Do the same check for the root's table after the loop. Return that maximum, or None if no node has a size-k entry.
Exercise
Why does the inner loop start at j = 1 instead of j = 0?
Show answer
b[0] is always -inf, because a set inside u's subtree that contains u needs at least one node. The case where u's subtree contributes nothing is already handled by copying a into merged.