I knew this was a tree DP problem pretty fast, but the rerooting part is where I fumbled.
Model the problem as finding, for each node, the number of edges that must be reversed to make it the root of an arborescence. First compute the answer for an arbitrary root using DFS, then reroot the tree to compute answers for all nodes in O(n) time. The key is to track how the reversal count changes when moving the root from a parent to its child.
Pro tip: Emphasize that the underlying undirected graph is a tree, so there are no cycles and exactly one path between any two nodes. This allows the rerooting technique to work in linear time, which is crucial for large n.
Clarify that for a given root, we need to count edges that are directed away from the root (i.e., need reversal to point towards the root). The answer for a node is the number of such edges.
Pick any node (e.g., 0) as root. Perform a DFS/BFS to compute the number of reversals needed for that root. For each edge, if it points from parent to child, it needs reversal; if from child to parent, it doesn't.
When moving the root from a parent u to a child v, the edge between them changes direction relative to the root. If the original edge was u->v, then for u it needed reversal (counted), but for v it does not; if v->u, then for u it did not, but for v it does. So the new count = old count + (1 if edge is v->u else -1).
Do a second DFS starting from the initial root, propagating the count to children using the transition. Store the result for each node.
The algorithm runs in O(n) time and O(n) space. Handle n=1 (answer 0) and ensure recursion depth is managed (use iterative DFS if needed).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.