[Solution] Masha and a Beautiful Tree Codeforces Solution
The girl named Masha was walking in the forest and found a complete binary tree of height and a permutation of length .
A complete binary tree of height is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is . The picture below shows the complete binary tree for .
A permutation is an array consisting of different integers from to . For example, [] is a permutation, but [] is not ( occurs twice), and [] is also not a permutation (, but there is in the array).
Let's enumerate leaves of this tree from left to right. The leaf with the number contains the value ().
For example, if , , the tree will look like this:
Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.
In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).
For example, if Masha applies this operation to the root of the tree discussed above, it will take the following form:
Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.
The first line contains single integer () — number of test cases.
In each test case, the first line contains an integer (), which is a power of two — the size of the permutation .
The second line contains integers: () — the permutation .
It is guaranteed that the sum of over all test cases does not exceed .
For each test case in a separate line, print the minimum possible number of operations for which Masha will be able to make the tree beautiful or -1, if this is not possible.
No comments:
Post a Comment