Sub topic 5
Take It or Leave It: Independent Set and Vertex Cover
This chapter assumes you can root a tree, get a pre-order from an iterative DFS, and walk that order in reverse so that children are handled before their parents. It also assumes you know the general idea of a DP state over a subtree. We reuse the root_tree helper from earlier chapters. It is copied into the code below so the examples run on their own.
Many tree problems ask you to pick a set of nodes under a local rule. The rule usually involves only a node and its neighbors: "no two chosen nodes are adjacent", or "every edge touches a chosen node". When the rule is that local, a subtree only has to report one fact upward: whether its root was chosen. That gives two states per node, and this chapter is about how to use them.
Why One Number Per Subtree Is Not Enough
Say you store only best[u], the best value inside the subtree of u. Now try to compute best[p] for a parent p. If you want to choose p, no child of p can be chosen. But best[c] might come from a set that contains c, and you can't tell from the number alone. The single number has lost the one fact the parent needs.
The fix is to split the state on that fact:
take[u]: the best value inu's subtree, given thatuis chosen.skip[u]: the best value inu's subtree, given thatuis not chosen.
Each child now gives its parent two numbers. The parent can then pick whichever child state its own decision allows. This is the general pattern. When a parent's choice limits its children, put the child's relevant decision into the child's state.
Maximum-Weight Independent Set
An independent set is a set of nodes in which no two nodes are joined by an edge. Each node u has a weight weight[u], and we want the independent set with the largest total weight.
The transition
Take a node u with children c1, c2, ...:
- If
uis chosen, every child must be skipped. The children's subtrees are otherwise independent of each other, so their best values add up:
take[u] = weight[u] + sum(skip[c])
- If
uis not chosen, each child is free. Each child takes whichever of its states is better:
skip[u] = sum(max(take[c], skip[c]))
Base case: for a leaf, take = weight[leaf] and skip = 0. You don't need a special case for this. Initialize take = weight and skip = 0 for every node, and a leaf never gets anything added. The answer is max(take[root], skip[root]).
The sums are valid because different children's subtrees share no nodes and no edges. The only edges that leave a child's subtree go up to u. So once u's decision is fixed, the children don't interact.
The constraints as a table
| Parent state | Allowed child states | Child contribution |
|---|---|---|
| take (chosen) | skip only | `skip[c]` |
| skip (not chosen) | take or skip | `max(take[c], skip[c])` |
A worked example
Use five nodes with edges 0-1, 0-2, 1-3, 1-4, rooted at 0, and weights [3, 2, 1, 4, 5].
Leaves first:
- Node 3: take = 4, skip = 0.
- Node 4: take = 5, skip = 0.
- Node 2: take = 1, skip = 0.
Node 1 has children 3 and 4:
- take[1] = 2 + skip[3] + skip[4] = 2 + 0 + 0 = 2
- skip[1] = max(4, 0) + max(5, 0) = 9
Node 0 has children 1 and 2:
- take[0] = 3 + skip[1] + skip[2] = 3 + 9 + 0 = 12
- skip[0] = max(2, 9) + max(1, 0) = 9 + 1 = 10
The answer is max(12, 10) = 12, from the set {0, 3, 4}. Check it: 0 is adjacent only to 1 and 2, and 3 and 4 are adjacent only to 1. None of the chosen nodes are adjacent, and 3 + 4 + 5 = 12.
Minimum Vertex Cover
A vertex cover is a set of nodes such that every edge has at least one endpoint in the set. We want the cover with the smallest total weight.
The rule is reversed. Here, leaving a node out is what restricts its children:
inc[u](u in the cover): every edge fromuto a child is already covered, so each child is free.
inc[u] = weight[u] + sum(min(inc[c], exc[c]))
exc[u](u not in the cover): the edgeu-cmust be covered byc, so every child must be included.
exc[u] = sum(inc[c])
The answer is min(inc[root], exc[root]).
| Parent state | Allowed child states | Child contribution |
|---|---|---|
| inc (in cover) | inc or exc | `min(inc[c], exc[c])` |
| exc (not in cover) | inc only | `inc[c]` |
On the same tree and weights:
- Leaves: inc[3] = 4, exc[3] = 0. inc[4] = 5, exc[4] = 0. inc[2] = 1, exc[2] = 0.
- Node 1: inc = 2 + 0 + 0 = 2, exc = 4 + 5 = 9.
- Node 0: inc = 3 + min(2, 9) + min(1, 0) = 5, exc = inc[1] + inc[2] = 2 + 1 = 3.
The minimum cover weighs 3, using the set {1, 2}.
The complement check
In any graph, a set S is independent exactly when its complement V \ S is a vertex cover. If an edge had both endpoints outside the cover, both endpoints would be in S, and that breaks independence. So:
minimum cover weight = total weight − maximum independent set weight
Here, 15 − 12 = 3, which matches. This gives you a free test: write both DPs, run them on random trees, and assert that the identity holds. On trees, which are bipartite, König's theorem also says that the minimum unweighted cover size equals the maximum matching size. That is a second independent check for the unweighted case.
Recovering the Chosen Set
The DP gives you the best value. Many problems also ask which nodes achieve it. Since every take and skip value is stored, you can go back down from the root in pre-order and make each decision the parent allows:
- The root is chosen if
take[root] > skip[root]. - If a node's parent is chosen, the node is skipped.
- Otherwise the node is chosen if
take[u] > skip[u].
This is consistent with the forward pass. When the parent is skipped, the forward pass used max(take[u], skip[u]) for u, and the top-down rule picks the side that achieved that maximum. Ties can go either way, as long as the comparison you use matches a value the forward pass could have taken.
Complete 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
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])
best = max(take[root], skip[root])
# Top-down reconstruction: pre-order visits parents before children.
chosen = [False] * n
for u in order:
p = parent[u]
if p != -1 and chosen[p]:
chosen[u] = False
else:
chosen[u] = take[u] > skip[u]
return best, [u for u in range(n) if chosen[u]]
def min_vertex_cover(n, edges, weight, root=0):
parent, order, _ = root_tree(n, edges, root)
inc = list(weight) # best cover of u's subtree with u in the cover
exc = [0] * n # best cover of u's subtree with u not in the cover
for u in reversed(order):
p = parent[u]
if p != -1:
inc[p] += min(inc[u], exc[u])
exc[p] += inc[u]
return min(inc[root], exc[root])
if __name__ == "__main__":
n = 5
edges = [(0, 1), (0, 2), (1, 3), (1, 4)]
weight = [3, 2, 1, 4, 5]
best, nodes = max_weight_independent_set(n, edges, weight)
cover = min_vertex_cover(n, edges, weight)
print("MWIS:", best, nodes) # MWIS: 12 [0, 3, 4]
print("Min cover:", cover) # Min cover: 3
assert cover == sum(weight) - best
# Unweighted cover on the same tree
print("Unweighted cover:", min_vertex_cover(n, edges, [1] * n)) # 2
# Single node, no edges
print(max_weight_independent_set(1, [], [7])) # (7, [0])Each pass touches every edge once, so both DPs run in O(n) time with O(n) memory. Neither one recurses, so a path of 200,000 nodes won't hit Python's recursion limit.
Edge Cases and Common Errors
Updating a parent before the child is final
The loop over reversed(order) adds u's values into its parent at the moment u is processed. That only works if take[u] and skip[u] are already final, which means all of u's children were processed earlier. Reverse pre-order guarantees this, because every descendant of u comes after u in pre-order. If you loop over order without reversing it, or over a BFS order in the wrong direction, you will silently add partial values.
Negative weights
The DP is an exact search over all valid assignments, so it stays correct with negative weights. take[u] may come out negative, and max will then prefer skip[u]. The empty set is always a valid independent set, so the answer is never below 0. If the problem requires a non-empty set, you need a different base case or a flag in the state.
Forests
If the input is a forest, root_tree from a single root only reaches one component. Either run the DP from an unvisited node in each component and add the answers, or add a virtual root joined to one node per component and give it weight 0 (for independent set) or treat it as forced-excluded, with care. Running per component is simpler and leaves less room for mistakes.
Mixing up the answer at the root
The answer is the better of the root's two states. Returning take[root] alone forces the root into the set. In the example that happens to be right, which is how the bug slips past a single test.
Integer overflow in other languages
Python integers don't overflow. In C++ or Java, the sums of weights along a 10^5-node tree with weights up to 10^9 need 64-bit integers.
Extending the Pattern
The two-state idea grows naturally whenever the local rule needs more information about the root.
| Problem | States per node | What the parent needs to know |
|---|---|---|
| Independent set | 2 | Is the child chosen? |
| Vertex cover | 2 | Is the child in the cover? |
| Dominating set | 3 | Is the child chosen, covered by its own child, or still uncovered? |
| Independent set with at most one chosen neighbor | 3 | Is the child chosen, and if so, does it already have a chosen neighbor? |
The design question is always the same: what is the smallest fact about a subtree's root that lets the parent check the rule on the parent-child edge? Every extra state multiplies the work per edge, so keep only the facts the parent actually reads.
Exercise
Change the independent set DP so that each node u is either chosen or not, and every edge must have at most one chosen endpoint, but you must also never choose two nodes that share a parent (siblings). What extra work does the transition for skip[u] need, given that take[c] and skip[c] are known for each child c?
Show answer
When u is skipped, at most one child may be chosen. Start from base = sum(skip[c]) over all children. Then skip[u] = base + max(0, max over c of (take[c] − skip[c])), where the term inside chooses the single most profitable child to switch to chosen. take[u] is still weight[u] + sum(skip[c]), since a chosen u already forbids every child.
Exercise
Write the three-state transition for minimum dominating set, where every node must be chosen or adjacent to a chosen node. Use a[u] = u chosen, b[u] = u not chosen but dominated by some child, c[u] = u not chosen and not yet dominated (its parent must be chosen).
Show answer
a[u] = weight[u] + sum(min(a[ch], b[ch], c[ch])). c[u] = sum(b[ch]), because no child is chosen and every child must already be dominated from below. b[u] = sum(min(a[ch], b[ch])) plus a correction that forces at least one child into state a: if some child has a[ch] <= b[ch] the correction is 0, otherwise it is the minimum over children of (a[ch] − b[ch]). A leaf has b = infinity. The answer is min(a[root], b[root]).
Exercise
On a path of 4 nodes 0-1-2-3 with weights [5, 1, 1, 5], compute take and skip for every node when rooted at 0, and report the maximum-weight independent set and the minimum vertex cover weight.
Show answer
Node 3: take 5, skip 0. Node 2: take 1 + 0 = 1, skip max(5, 0) = 5. Node 1: take 1 + 5 = 6, skip max(1, 5) = 5. Node 0: take 5 + 5 = 10, skip max(6, 5) = 6. The MWIS is 10 with set {0, 3}. The minimum vertex cover is 12 − 10 = 2 with set {1, 2}.