Pattern
DP on Trees
dp[v][state] computed from children's dp values in post-order (e.g. take/skip v, cover state, matched or not).
0/19 solved
Recognise it
The signal
choose a set of nodes on a tree with adjacency constraints
1Brute force
Enumerate subsets of nodes.
2The observation
Exponential subsets: each subtree's answer depends only on its root's state.
3Why it works
dp[v][s] is optimal for v's subtree given v is in state s.
Reach for it when
- +cameras/guards/matching on tree
- +count/optimise over subtrees
Not when
- ×answer needed for every root (rerooting)
- ×path queries (binary-lifting / hld)
Practice
- White-Black Balanced SubtreesCodeforces1300
- Tree Distances IICSESMedium
- Tree Distances ICSESMedium
- Maximum White SubtreeCodeforces1800
- House Robber IIIMedium
- Tree MatchingCSESMedium
- Kingdom and its CitiesCodeforces2800
- Count PathsCodeforces2000
- Karen and SupermarketCodeforces2400
- Berland FederalizationCodeforces2200
- Tree PaintingCodeforces2100
- Sum of Distances in TreeHard
Pitfalls
Misconceptions
- !greedy on trees often fails where DP works (e.g. house robber III)
Go deepervariants and techniques · 3 combinations · resources
Variants and techniques
Combinations
Rerooting DP (all roots)+DP on Trees
sum of distances from every node; best value when each node is the root
- Rerooting DP (all roots):
- propagates outside-subtree info to children
- DP on Trees:
- computes answers for subtrees from one root
Virtual (Auxiliary) Tree+DP on Trees+Binary Lifting & LCA
many queries with a small vertex set each and sum of k bounded
- Virtual (Auxiliary) Tree:
- shrink the tree to the O(k) marked vertices and their LCAs
- DP on Trees:
- run the separation/cover DP on the small tree
- Binary Lifting & LCA:
- LCA queries while building the virtual tree
DP on Trees+Combinatorics mod p (nCr, Catalan, stars and bars)
count the orders in which tree nodes can be added parent-first (or BST insert orders)
- DP on Trees:
- subtree sizes and the ways for each child
- Combinatorics mod p (nCr, Catalan, stars and bars):
- interleave the children's orders with multinomials, i.e. n! / product of subtree sizes
Count Ways to Build Rooms in an Ant ColonyNumber of Ways to Reorder Array to Get Same BST