#P8046. [COCI 2015/2016 #4] CHEWBACCA
[COCI 2015/2016 #4] CHEWBACCA
Background
Problem T3 of this contest set is P8053.
Problem Description
A -ary tree with nodes is constructed in the following way:
- First, create a root node and label it as .
- Then repeat the following steps until the total number of nodes is exactly :
- Let the label of the last newly added node be .
- In the previous level, scan from left to right to find the first node whose number of children is .
- If this node has no children, add a child node under it, label it as , and connect node and the parent node we found with an edge of length .
- Otherwise, add a new child node immediately to the right of the most recently added child of this node, label it as , and connect node and the parent node we found with an edge of length .
- If no node with number of children is found in the current level, move to the next level.
For example, the figure below shows a -ary tree with nodes constructed by the method above:

Now you are given this -ary tree with nodes, and you need to answer queries. Each query gives two integers , and you need to output the length of the shortest path from node to node in this tree.
Input Format
The first line contains three integers , representing the number of nodes in the tree, the arity, and the number of queries.
Then follow lines, each containing two integers , representing the two nodes in the query.
Output Format
Output lines, each containing one integer, the length of the shortest path between node and node .
7 2 3
1 2
2 1
4 7
1
1
4
9 3 3
8 9
5 7
8 4
2
2
3
Hint
[Sample 1 Explanation]
The figure below shows the tree constructed in sample 1:

It is easy to see that for the st and nd queries, since node is a child of node , the shortest path length between these two nodes is exactly . For the rd query, one shortest path is $4\rightarrow 2\rightarrow 1\rightarrow 3\rightarrow 7$. Therefore, the shortest path length is .
[Sample 2 Explanation]
The tree constructed in sample 2 can be found in the “Description” section.
[Constraints]
For of the testdata, is guaranteed.
For of the testdata, is guaranteed.
For all testdata, , , .
[Source]
This problem comes from COCI 2015-2016 CONTEST 4 T4 CHEWBACCA. Using the original problem’s data configuration, the full score is points.
Translated and organized by Eason_AC.
Translated by ChatGPT 5