Sub topic 5
Take It or Leave It: Independent Set and Vertex Cover
This chapter assumes you can root a tree and get a post-order with the root_tree helper from earlier chapters, and that you are comfortable with array DP and Big-O analysis. Here you add a second dimension to the state: whether the subtree's root is chosen or not chosen.
The problem shape
Many tree problems ask you to pick a set of nodes under a rule that connects each node to its neighbors. Two classic ones:
- Maximum-weight independent set: choose nodes so that no two chosen nodes share an edge, and maximize the total weight.
- Minimum vertex cover: choose nodes so that every edge has at least one chosen endpoint, and minimize the count.
A single number per subtree, such as "best value in u's subtree", is not enough. The parent needs to know whether u itself was chosen, because that decides which choices the parent may make. So each node keeps two values:
| State | Meaning |
|---|---|
| `take[u]` | best value in u's subtree, given u is chosen |
| `skip[u]` | best value in u's subtree, given u is not chosen |
Independent set transitions
If u is chosen, none of its children can be chosen:
take[u] = weight[u] + sum(skip[c] for each child c)
If u is skipped, each child is free, so it takes whichever state is better:
skip[u] = sum(max(take[c], skip[c]) for each child c)
The base case is a leaf, which gets take = weight, skip = 0. You don't need special code for leaves: they have no children, so the initial values are already right.
Code
The pass walks the post-order in reverse, so every child is final before it is added to its parent. Each child pushes its contribution up to its parent, which means you never need a child list.
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 max_weight_independent_set(n, edges, weight, root=0):
parent, order, _ = root_tree(n, edges, root)
take = list(weight) # best value in u's subtree with u chosen
skip = [0] * n # best value in u's subtree with u not chosen
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 min_vertex_cover(n, edges, root=0):
parent, order, _ = root_tree(n, edges, root)
take = [1] * n # min cover of u's subtree with u in the cover
skip = [0] * n # min cover of u's subtree with u not in the cover
for u in reversed(order):
p = parent[u]
if p != -1:
take[p] += min(take[u], skip[u])
skip[p] += take[u] # edge (p, u) must be covered by u
return min(take[root], skip[root])
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
print(max_weight_independent_set(5, edges, [3, 2, 1, 4, 5])) # 12
print(min_vertex_cover(5, edges)) # 2Tracing the example
Node 1 has leaf children 3 (weight 4) and 4 (weight 5). That gives take[1] = 2 + 0 + 0 = 2 and skip[1] = 4 + 5 = 9. At the root, take[0] = 3 + skip[1] + skip[2] = 3 + 9 + 0 = 12 and skip[0] = max(2, 9) + max(1, 0) = 10. The answer is 12, from the set {0, 3, 4}.
Vertex cover follows the same pattern with the rule turned around. Skipping u forces every child to be taken, because the edge between u and that child still needs a chosen endpoint.
Common errors
- One state only. If you store just "best in subtree", you lose the information the parent needs to obey the adjacency rule.
- Mixing up which side is forced. In independent set, taking the parent forces the children's state. In vertex cover, skipping the parent does. Write each rule out in words before you code it.
- Returning only
take[root]or onlyskip[root]. The root has no parent constraining it, so return the better of the two. - Negative weights. The code above handles them correctly, because
skiplets the DP leave out a negative node. Don't clamptaketo zero, since that would quietly allow two adjacent nodes to be chosen. - Recursive DFS on deep trees. A path of 10^5 nodes overflows Python's recursion limit. The iterative order avoids this.
Both passes run in O(n) time and use O(n) memory.
Exercise
Change minvertexcover to minimize total cost, where node u costs cost[u] >= 0. Which lines change?
Show answer
Initialize take = list(cost) instead of [1] * n. The transitions stay the same: take[p] += min(take[u], skip[u]) and skip[p] += take[u].
Exercise
On the path 0-1-2-3 with weights [5, 1, 1, 5], what does maxweightindependent_set return, and which set achieves it?
Show answer
10, from {0, 3}. Root at 0: node 3 gives take=5, skip=0. Node 2 gives take=1, skip=5. Node 1 gives take=1+5=6, skip=max(1,5)=5. Node 0 gives take=5+5=10, skip=max(6,5)=6. The maximum is 10.
Exercise
Why does skip[p] in vertex cover add take[u] rather than min(take[u], skip[u])?
Show answer
If p is not in the cover, the edge (p, u) can only be covered by u, so u must be chosen.