Editorial
Problem Author: | Maksym Shvedchenko |
Prepared by: | Maksym Shvedchenko |
Editorial by: | Illia Shevchenko |
Fact 1: for the resulting tree (with ), the height of the tree is at most 22.
Group 1: .
It is possible to construct trees.
Now, in the query, we have 2 vertices and we need to find the distance between them. This is a standard problem for DFS or BFS.
Group 2: .
It is possible to construct trees.
For each vertex, we will maintain its depth in the tree.
For each query, for each vertex, find the list of vertices above it. Find the deepest vertex that is in both lists (it always exists, as vertex 1 belongs to both lists). Let's call this vertex .
The answer to the query will be the depth of vertex + the depth of vertex - 2 * (the depth of ).
The complexity of the solution is , where is the depth of the tree, and the memory is .
Group 3: .
Notice that at each depth, there will be vertices within a certain range from to .
For each depth , we will maintain 2 numbers such that the numbers of all vertices at depth are within the range , and there are no vertices with other depths within the range .
We will maintain this for the height. For height 1, this is the range . Then, we iterate through all heights from 2 to 22 and recalculate the range.
If at height the range is , then at height the range is , where is the total number of bits in the numbers from to .
can be calculated by iterating through all bits from 0 to 61 and finding the number of bits in the prefix and subtracting the number in the range .
Next, we need to learn how to find the parent for a vertex. We can find its depth using binary search and an array of ranges. Then, we take the depth one less and, using binary search and the function , find the parent of the vertex.
The answer to the queries will be the same as in the second subgroup, but we will find the depth and parent of the vertex using the methods described above in the tutorial.
The complexity of the solution is , where is the depth of the tree.
Group 4: .
Asymptotically, the solution remains the same, but we can simply reduce the constant.
For example, when calculating in binary search to find the parent, we notice that there will be log queries with the same , which means we can calculate the number of bits in the range once.