Editorial for COCI '13 Contest 5 #2 Obilazak
Submitting an official solution before solving the problem yourself is a bannable offence.
Firstly, we will enumerate the nodes in the tree in the following way: the root is number , its left child is number and its right child is number . Generally, the left child of a node is numbered with and the right child is numbered with .
Mirko walks around visiting the buildings following this recursive algorithm:
visit(x)
if x < 2^K-1, visit(2 * x)
write down x on paper
if x < 2^K-1, visit(2 * x + 1)
We can construct a "reverse" recursive function which will reconstruct a tree for a given route of visits. We will use an array tree[]
where the item is going to be a label of the node and a counter p
which is initially set to .
return(x)
if x < 2^K-1, return(2 * x)
tree[x] = route[p]
p = p + 1
if x < 2^K-1, return(2 * x + 1)
In the end, we output items of the array tree[]
.
The task could have been solved without recursion, with noticing regularities in the route of visits of the tree. Consult the source code for this type of solution.
Comments