Sub topic 14
Branch and Bound with a Fractional Bound
The dynamic programming solutions earlier in this tutorial run in O(nW) time. That works when the capacity W is a few thousand or a few million. When weights are measured in grams across a shipping container, or in bytes across a disk, W can reach 10^12, and no table of that size fits in memory. Branch and bound handles that case another way. It searches the same subset tree as brute force, but it skips any branch that provably cannot beat the best solution found so far.
This chapter assumes you know the brute-force subset search, the greedy algorithm for fractional knapsack, and the reason greedy fails for 0/1 knapsack. It also assumes you can read recursive Python.
The Idea: Search the Tree, Skip What Cannot Win
Brute force builds a binary tree. Level i decides whether item i is taken or skipped, and each leaf is one of the 2^n subsets. Branch and bound walks the same tree depth-first and keeps two quantities:
- The incumbent is the value of the best feasible solution found so far.
- The upper bound of a node is a number guaranteed to be at least the value of every solution in that node's subtree.
If a node's upper bound is no greater than the incumbent, nothing below it can improve the answer, so the algorithm prunes it. How well this works depends almost entirely on how tight the bound is and how fast it can be computed.
Why the Fractional Solution Is a Valid Bound
At a node we have already decided items 0 to i−1. We hold a current value value and remaining capacity room. Every completion of this node picks some subset of items i to n−1 that fits in room.
The fractional knapsack problem on those same remaining items with capacity room lets us take parts of items. Every 0/1 choice is also a legal fractional choice, so the fractional optimum is at least the 0/1 optimum. The fractional problem is a relaxation of the 0/1 problem: it drops a constraint, so its optimum can only stay the same or grow. Its optimum therefore bounds every completion from above:
upper bound = value + fractional optimum of items i..n−1 with capacity room
The greedy algorithm solves the fractional problem exactly. If the items are sorted by value-to-weight ratio once at the start, the bound becomes a single left-to-right scan. Take whole items while they fit, then take a fraction of the first one that doesn't.
Implementation
def knapsack_bb(values, weights, capacity):
# Assumes every weight > 0. Items are sorted once by value density.
items = sorted(zip(values, weights), key=lambda it: it[0] / it[1], reverse=True)
n = len(items)
best = 0
def bound(i, value, room):
# Optimal fractional value using items i..n-1 with capacity room.
for v, w in items[i:]:
if w <= room:
room -= w
value += v
else:
return value + v * room / w
return value
def search(i, value, room):
nonlocal best
if value > best:
best = value
if i == n or bound(i, value, room) <= best:
return
v, w = items[i]
if w <= room:
search(i + 1, value + v, room - w) # take branch first
search(i + 1, value, room) # then skip branch
search(0, 0, capacity)
return best
print(knapsack_bb([60, 100, 120], [10, 20, 30], 50)) # 220Three details matter here.
- The incumbent is updated at every node, not only at leaves. Any partial selection is already a feasible solution, because skipping all the remaining items is always allowed.
- The pruning test uses
<=. A subtree whose best possible value only ties the incumbent cannot produce a strictly better answer. - The take branch is explored first. Following the greedy order down the take branches quickly produces a near-greedy solution, and that gives the pruning test something to compare against.
Tracing the Example
Name the items A = (60, 10), B = (100, 20), C = (120, 30). They are already in ratio order: 6, 5, 4.
The search first reaches 160, which is the greedy answer, and then improves it twice. Once the incumbent is 220, the subtree under "skip A, skip B" is pruned, because even its fractional bound of 120 falls short. On three items the saving is small. On hundreds of items with a tight bound, most of the tree is never visited.
Checking It Against DP
Any pruning rule should be tested against a trusted solver on random instances.
import random
def knapsack_dp(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def knapsack_bb(values, weights, capacity):
items = sorted(zip(values, weights), key=lambda it: it[0] / it[1], reverse=True)
n = len(items)
best = 0
nodes = 0
def bound(i, value, room):
for v, w in items[i:]:
if w <= room:
room -= w
value += v
else:
return value + v * room / w
return value
def search(i, value, room):
nonlocal best, nodes
nodes += 1
best = max(best, value)
if i == n or bound(i, value, room) <= best:
return
v, w = items[i]
if w <= room:
search(i + 1, value + v, room - w)
search(i + 1, value, room)
search(0, 0, capacity)
return best, nodes
random.seed(1)
for _ in range(200):
n = random.randint(1, 18)
values = [random.randint(1, 100) for _ in range(n)]
weights = [random.randint(1, 60) for _ in range(n)]
cap = random.randint(0, sum(weights))
got, nodes = knapsack_bb(values, weights, cap)
assert got == knapsack_dp(values, weights, cap)
print("all match; last instance visited", nodes, "nodes of", 2 ** (n + 1) - 1)On random uncorrelated instances like these, the node count is usually a small fraction of the full tree.
Failure Modes and Gotchas
The worst case is still exponential
Pruning does not change the worst case, which remains O(2^n) nodes. Branch and bound is a heuristic speed-up of an exact search, not a polynomial algorithm. Instances where value is close to weight plus a constant (strongly correlated instances) are notoriously hard. Every item has nearly the same ratio, so the fractional bound sits just above many different subsets, and few branches get pruned.
Bound cost per node
The scan in bound costs O(n) per node. A common fix precomputes prefix sums of the sorted weights and values. A binary search then finds the first item that doesn't fit, which brings the bound down to O(log n) per node. The fix only applies when the remaining items are a contiguous suffix, which is true in this depth-first scheme.
Floating point and integer values
The fractional term v * room / w is a float. With integer values the true optimum is an integer, so you can use floor(bound) and still prune safely, which slightly strengthens the test. Beware of very large values, where float rounding could push the bound below the true fractional value. In that case, compare value * w + v * room against best * w in integers.
Zero-weight items
The ratio divides by weight, so the code assumes w > 0. Items with weight 0 and positive value should always be taken, so add their value up front and remove them before sorting.
Search order variants
Depth-first search uses O(n) memory and finds incumbents quickly. Best-first search keeps a priority queue of open nodes and always expands the one with the highest bound. It often visits fewer nodes, but the queue can grow exponentially. Depth-first is the usual default. A greedy solution computed before the search gives a good starting incumbent at almost no cost.
When to Choose Branch and Bound
| Situation | Better choice |
|---|---|
| W up to about 10^7, any n | Weight-indexed DP, O(nW) |
| Huge W, small total value | Value-indexed DP |
| Huge W, n up to about 40, need guaranteed time | Meet in the middle |
| Huge W, n in the hundreds or more, uncorrelated data | Branch and bound |
| Huge W and values, near-optimal is acceptable | FPTAS |
| Strongly correlated items, huge W | Expect trouble; combine bounds or accept approximation |
Branch and bound is the only method in this table whose running time does not depend on W or on the size of the values at all. That makes it a strong first choice when the numbers are large and the data is not adversarial.
Exercise
In the traced example, suppose the search explored the skip branch before the take branch at every node. Would the "skip A, skip B" node (bound 120) still be pruned, and why does exploration order matter in general?
Show answer
Yes. With skip-first order, the "skip A, skip B" subtree is reached early, while the incumbent is still 0, so it is not pruned. The search explores it and finds C alone for 120. That subtree is entered before any better solution exists, so it gets expanded instead of cut. In general, pruning compares bounds against the incumbent, and exploring the greedy (take-first) direction early produces a high incumbent sooner. Every later comparison then prunes more.
Exercise
Explain why replacing the fractional bound with "value + sum of values of all remaining items" still gives a correct algorithm, and what it costs.
Show answer
The sum of all remaining values is also at least the value of any completion, so it is a valid upper bound and no optimal solution is ever pruned wrongly. It ignores capacity, though, so it is much looser than the fractional bound. Far fewer nodes get pruned, and the search behaves close to brute force. A looser bound never breaks correctness. It only slows the search.