Sub topic 10
The Size-Bounded Merge Argument
The previous chapter merged child tables into a parent's table for tree knapsack. Each merge was a double loop over two tables. That looks expensive. A node can have many children, each table can have up to k + 1 entries, and a naive bound gives O(n·k²). This chapter shows that the real cost is O(n·k), as long as you write the loops the right way. It also shows which small coding mistakes push the cost back up to O(n·k²) or worse.
This chapter assumes you know the root_tree helper and the best_rooted_subtree function from earlier chapters, Big-O analysis, and the idea of a lowest common ancestor (LCA), the deepest node that has both of two given nodes in its subtree.
What a Merge Actually Costs
Recall the core of the tree knapsack merge:
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]Here a is the parent's table so far. It covers the parent plus the children already merged into it. b is the finished table of one child. Two facts control the cost:
- A table that covers s nodes has length min(s, k) + 1. It cannot hold more entries than there are nodes, and the cap stops it at k.
- The double loop runs at most (len(a) − 1)·(len(b) − 1) times.
So if the part already merged into the parent has s₁ nodes and the child's subtree has s₂ nodes, the merge costs at most min(s₁, k)·min(s₂, k). The whole argument rests on that one expression.
Warm-up: Without a Cap, the Total Is O(n²)
First set k = n, so nothing is capped. A merge then costs s₁·s₂. Think of that product as the number of pairs (x, y) where x is a node in the parent's accumulated part and y is a node in the child's subtree.
Each pair of nodes is counted in exactly one merge. Before the merge at their LCA, x and y sit in different parts. After it, they share a part, and no later merge counts a pair from inside a single part. There are n(n − 1)/2 pairs, so the total work over the whole tree is O(n²).
This pair-counting view is the tool for the capped case too. The cap only lowers the cost, and the next section shows it lowers it to O(n·k).
The Capped Case: Three Kinds of Merges
Call a part big if it has at least k nodes and small otherwise. Every merge combines two disjoint parts, which gives three cases.
Case 1: Big + Big
Each such merge costs at most k·k. To count these merges, look at minimal big parts: parts that became big through a small + small merge, or that were big from the start. A minimal big part was built only from small parts, so it contains no other big part. Two parts in the merge history are either nested or disjoint, so the minimal big parts are pairwise disjoint. Each one has at least k nodes, so there are at most n/k of them.
Every big part descends from one or more minimal big parts. A big + big merge joins two of these lineages into one. Starting from at most n/k lineages, you can do at most n/k − 1 such joins. The total is at most (n/k)·k² = n·k.
Case 2: Big + Small
Let the small side have s < k nodes. The cost is at most k·s. Charge k to each node on the small side. After this merge, those nodes belong to a big part, and a part never shrinks. So no node is on the small side of a big + small merge twice. Each node is charged k at most once, and the total is at most n·k.
Case 3: Small + Small
The cost is s₁·s₂, which counts pairs of nodes, as in the warm-up. Follow a node x through the merges. While its part stays small, it takes part in small + small merges. The last such merge produces a part of fewer than 2k nodes, since both inputs had fewer than k. Every pair charged to x in this case lies inside that final group. Such groups are disjoint, and a group of g nodes holds fewer than g·g/2 pairs, with g < 2k. Summing over groups gives fewer than n·2k/2 = n·k pairs.
Adding It Up
| Merge type | Cost per merge | Why the total is bounded | Total |
|---|---|---|---|
| Big + big | ≤ k² | At most n/k − 1 lineage joins | ≤ n·k |
| Big + small | ≤ k·s | Each node is on the small side once | ≤ n·k |
| Small + small | ≤ s₁·s₂ | Pairs inside disjoint groups of size < 2k | < n·k |
The total is below 3·n·k, which is O(n·k). The i + j > k break in the real code only removes iterations, so the bound still holds. Notice that the argument never relies on the order in which children are merged. Any order works.
Checking the Bound Empirically
The script below counts the inner-loop iterations the knapsack merge would perform, without doing the DP itself. It compares two versions:
- The correct version: table lengths follow min(size merged so far, k) + 1.
- The naive version: every table is allocated at full length k + 1 from the start, and both loops run over the whole range.
The count uses a closed form for each row of the double loop, so even large inputs finish quickly.
import random
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
def loop_count(a_len, b_len, k):
# iterations of: for i in 1..a_len-1, for j in 1..b_len-1, break if i+j>k
total = 0
for i in range(1, a_len):
total += max(0, min(b_len - 1, k - i))
return total
def merge_work(n, edges, k, naive=False):
parent, order, _ = root_tree(n, edges, 0)
length = [2] * n # each table starts as [NEG, value[u]]
work = 0
for u in reversed(order):
p = parent[u]
if p == -1:
continue
if naive:
work += k * k # both loops always run over 1..k
else:
work += loop_count(length[p], length[u], k)
length[p] = min(length[p] + length[u] - 1, k + 1)
return work
def make_tree(kind, n):
if kind == "path":
return [(i - 1, i) for i in range(1, n)]
if kind == "star":
return [(0, i) for i in range(1, n)]
if kind == "caterpillar":
spine = n // 2
edges = [(i - 1, i) for i in range(1, spine)]
edges += [(i - spine, i) for i in range(spine, n)]
return edges
rng = random.Random(1)
return [(rng.randrange(i), i) for i in range(1, n)]
n = 20000
for k in (10, 100, 1000):
for kind in ("path", "star", "caterpillar", "random"):
edges = make_tree(kind, n)
good = merge_work(n, edges, k)
bad = merge_work(n, edges, k, naive=True)
print(f"k={k:5} {kind:12} work/(n*k)={good / (n * k):6.3f}"
f" naive/(n*k)={bad / (n * k):9.1f}")In the correct version, the ratio work/(n*k) stays below 3 for every tree shape and every k, as the proof predicts. For the path and the star it is well below 1. In the naive version, the ratio is about k, because the naive cost is roughly n·k². At k = 1000 that is about a thousand times more work.
Mistakes That Break the Bound
The proof assumes that each table's length matches the number of nodes it covers, capped at k. Each mistake below breaks that assumption in a different way.
Looping Over k Instead of the Table Length
# Wrong: always O(k^2) per edge, O(n*k^2) total
for i in range(k + 1):
for j in range(k + 1 - i):
...Even a leaf's table, which has only entries 0 and 1, gets scanned k times. This is the most common way to lose the bound. Loop over the actual table lengths and let them grow.
Using the Final Subtree Size for the Parent
Suppose you allocate the parent's table with length min(size[p], k) + 1 before merging any children, and loop over all of it. With k = n on a path, the merge at a node whose subtree has s nodes then costs about s·(s − 1). Summed along the path, that is about n³/3 instead of n². The pair-counting argument works only because a covers exactly the nodes merged so far.
Forgetting the Cap After Merging
If merged has length len(a) + len(b) − 1 without the min(…, k + 1), tables grow past k + 1. Sizes up to n then enter the cost, and you are back to the O(n²) of the uncapped case. That is acceptable only when k is close to n.
Skipping Empty Entries Is an Optimization, Not the Proof
The if a[i] == NEG: continue line saves time in practice, but the bound does not depend on it. Do not drop the cap or the growing lengths because you expect most entries to be −∞.
Memory and Variants
The code sets dp[u] = None after merging a child. In a post-order walk, the live tables are the finished children waiting for their parent and the partial table of each node on the current path. In the worst case, such as a star, that is still Θ(n·k) entries, but freeing tables helps a lot on typical inputs. If memory is tight, process children one at a time in a DFS so that only the tables along the current path stay alive.
The argument carries over to related state designs:
| Variant | Effect on the bound |
|---|---|
| Size index plus a small flag (for example, take/skip per size) | Multiplies the cost by a constant (4 for two flags on each side) |
| Allow j = 0 (empty selection) | Same lengths and same bound |
| Cap at k but only `dp[root][k]` is needed | Same O(n·k); the cap is what makes it work |
| No cap (k = n) | O(n²) by pair counting at the LCA |
| Weighted items, index is total weight up to W | The bound fails if weights are large; the cost can reach O(n·W²) |
The last row matters. The proof uses the fact that a part of s nodes has at most s + 1 useful entries. When the index is a total weight rather than a node count, a single node can fill a large range of the table, and the size-based argument no longer applies.
Exercise
A student writes the merge with correct growing lengths but no cap, then calls it with k = 50 on a tree of n = 100,000 nodes. What is the worst-case cost, and which one-line change brings it down to O(n·k)?
Show answer
Without the cap, table lengths grow with subtree size, so the cost follows the uncapped pair-counting bound, O(n²), which is about 10^10 here. Capping the merged length with min(len(a) + len(b) - 1, k + 1) (and breaking when i + j > k) restores O(n·k), about 5·10^6.
Exercise
In the big + small case, why can a node never be charged twice, even though its part keeps taking part in later merges?
Show answer
After the merge, the node belongs to a big part, and parts only grow, so it stays in a big part. In any later merge, it is on a big side, either in a big + small merge (where only the small side is charged) or in a big + big merge (which is counted separately through lineage joins). It can never be on the small side again.
Exercise
On a path of n nodes rooted at one end, with k = n, compute the exact number of inner-loop iterations of the correct merge, ignoring the i + j > k break. Compare it with the version that pre-allocates the parent's table to its final subtree size.
Show answer
Each merge joins a parent's table covering 1 node (length 2) with a child's subtree of s − 1 nodes, costing 1·(s − 1). Summed over s = 2..n, that is n(n − 1)/2, which equals the number of node pairs. With pre-allocation to the final size s, each merge costs s·(s − 1), and the sum is about n³/3.