Editorial
By the standard endpoint-normalization and long-move exchange lemmas, an optimum exists in one of the following forms.
- The deleted and added edges share one endpoint .
- If is not a leaf, the old and new attachment vertices are at distance at most .
- If is a leaf, the new attachment vertex may be arbitrarily far away.
Delete and add . Let be the component containing after the deletion, and let . Distances inside either component do not change. For every and every vertex in the other component, the distance changes exactly when
If is odd, every such changes. If it is even, only the two path-direction branches at the midpoint contribute.
For distance , the cost is . For distance , along the path , let be the size of the side of , let be the size of the branch at , and let be the size of the branch at . The cost is
Both expressions are concave in , so only the minimum and maximum available branch sizes are needed. Keeping the two smallest and two largest branch sizes at every vertex handles all distance- and distance- candidates in linear time.
For a leaf move with an even old-to-new attachment distance, let be the midpoint. Let be the branch containing the moved leaf and the branch containing the new attachment vertex. The cost is
For every directed branch from a center vertex, compute its size , maximum depth , and nearest original-leaf distance . Branch is usable when , and another branch is usable when
Thus each branch asks for the minimum size of another branch whose height is at least a threshold.
All directed-branch values are computed with rerooting DP. Sort branch records by center and decreasing height, and sort queries by center and decreasing threshold. Since every key is an integer between and , stable counting sort makes both orderings linear. During the sweep, maintain the two smallest active branch sizes so that the query branch itself can be excluded.
The total time complexity is and the memory complexity is .
Solution written by GPT5.6