##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
You've done DP on general graphs. Now use tree structure. Solve rerooting DP problems where you compute answers for every node as root.
Connected, no cycles, n-1 edges
Hierarchies, file systems, game trees
LC 2581 - count valid root nodes
Reroot: one root's answer to another
correct[v] = guesses when rooted at v
Edge flip: +1 or -1 to count
Root at 0, count initial correct
Two DFS: first root, then reroot
The rerooting template
O(n + g) for g guesses
The binary lifting template
LC 3203 - connect two trees optimally
Merged diameter ≥ max original
Connect centers, not random nodes
Two BFS finds diameter endpoints
max(d1, d2, r1 + r2 + 1)
LC 2858 - reversals for reachability
Edge toward root costs 1
0 for forward, 1 for backward
Reroot adjusts reversal count
Cost delta when moving root
LC 1443 - collect apples, return home
The merging technique
Traverse edge if subtree has apples
2 * edges_with_apples_below
Which tree technique?
When to reroot?
Undirected but stored directed
CF 1406C - fix centroids
The solution
CF 570D - subtree queries
The solution
CF 613D - virtual tree
The solution
CSES - tree structure
The solution
SPOJ COT2 - path counting
The solution
Rerooting to binary lifting