Editorial for DMOPC '15 Contest 7 P5 - Ariadne's Thread
Submitting an official solution before solving the problem yourself is a bannable offence.
If we start from the root node and follow the described method of traversal, the resulting order of visiting nodes is known as the Euler tour representation of the tree, which we can store in an array. From here we notice that no matter which nodes are our starting and ending points, we can divide the resultant path into segments that can be found within this array.
Our next observation should be that the required path will always visit the lowest common ancestor (LCA) of and before reaching . Keeping this in mind, we have two cases:
- is visited before in the Euler tour.
- is visited after in the Euler tour.
Let be the LCA of and . In the first case, it is easy to see that all nodes in the subtree rooted at that are before in the Euler tour will be visited regardless of 's position in the subtree. The length of the path is therefore the first visiting time of - the first visiting time of - the distance from to .
The second case is a little more tricky and is left to the reader as an exercise.
Time Complexity:
Comments