Editorial for Back From Summer '19 P5: ABC123E
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Note that we can replace the average of the lengths of the paths with the sum of the lengths of the paths, as the question's answer will not change.
For the first subtask, we can run DFSs for each question. From each node in the tree, we can run a Depth First Search (DFS) to find the sum of the lengths of the paths originating from that node.
Time Complexity:
For the second subtask, there were multiple different ways to find the sum of the lengths of the paths. However, we needed to be able to answer each question in subquadratic time in order to pass. One way to find the answer is to perform centroid decomposition on the tree. Another way is to perform dynamic programming on the tree. We will describe the dynamic programming solution.
Let represent the number of nodes in 's subtree, including . Let represent the sum of the path lengths from all of the nodes in 's subtree to . Thus, , where is a child of . Let represent the sum of the path lengths from all nodes not in 's subtree to . Thus, , where is the parent of . It is left as an exercise for the reader to prove these.
The sum of the length of the paths to is .
Time Complexity: or
For the last subtask, we needed to achieve sublinear time per question. Instead of calculating the sum of the lengths of the paths, we will now calculate how much the sum changed.
We will use the same definitions of , , and as subtask 2. In addition, we will define as the length of the path from to . To calculate , we can use a sparse table and Lowest Common Ancestor (LCA). Note that there are several other ways to do this.
Notice that when nodes and are swapped, only the path lengths from a node in 's subtree to a node outside both node and node 's subtree have changed length, and similarly with the nodes in 's subtree. This means that any paths whose endpoints are outside of both and 's subtree have not changed length.
To calculate the change, we need to subtract the sum of the lengths of the paths from all nodes in 's subtree to all nodes outside of both subtrees. It turns out, this value is exactly . Note that we do not need to account for the path section from a descendant of to , as it will be added later on after moving the subtree.
Then, we need to add the sum of the lengths of the paths after moving the subtree. It turns out, this value is exactly . Note that we do not need to account for the path section from a descendant of to , for the same reason as above (but this time added).
We need to do the same thing for 's subtree, which should result in:
Cleaning up the expression gives us:
Time Complexity:
Comments