Technique
Rerooting DP (all roots)
Compute subtree DP once, then pass 'everything outside this subtree' from parent to child to get the answer for every root in O(n).
Learn firstDP on Trees
0%
mastery
0/7 solved
0/7 solved
Recognise it
The signal
answer for every vertex as the root
1Brute force
Run the tree DP from each root: O(n2).
2The observation
Recomputing whole-tree DP per root: only the parent-side contribution changes when the root moves one edge.
3Why it works
up[v] equals the DP value of the tree outside v's subtree, viewed from v.
Reach for it when
- +sum of distances from each node
- +max distance from each node
Not when
- ×merge operation not invertible and no prefix/suffix trick
- ×single root suffices
Practice
0/7 solved
- Tree Distances IICSESMedium
- Tree Distances ICSESMedium
- Maximum White SubtreeCodeforces1800
- Tree PaintingCodeforces2100
- Sum of Distances in TreeHard
- Tree with Maximum CostCodeforces1900
- Tree Coin Collecting IICSESHard
Pitfalls
Misconceptions
- !using subtraction for non-invertible merges like max (needs prefix/suffix maxima)
Go deeper1 combinations · resources
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