CF1741D.Masha and a Beautiful Tree

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

The girl named Masha was walking in the forest and found a complete binary tree of height nn and a permutation pp of length m=2nm=2^n .

A complete binary tree of height nn 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 nn . The picture below shows the complete binary tree for n=2n=2 .

A permutation is an array consisting of nn different integers from 11 to nn . For example, [ 2,3,1,5,42,3,1,5,4 ] is a permutation, but [ 1,2,21,2,2 ] is not ( 22 occurs twice), and [ 1,3,41,3,4 ] is also not a permutation ( n=3n=3 , but there is 44 in the array).

Let's enumerate mm leaves of this tree from left to right. The leaf with the number ii contains the value pip_i ( 1im1 \le i \le m ).

For example, if n=2n = 2 , p=[3,1,4,2]p = [3, 1, 4, 2] , 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 tt ( 1t1041 \le t \le 10^4 ) — number of test cases.

In each test case, the first line contains an integer mm ( 1m2621441 \le m \le 262144 ), which is a power of two — the size of the permutation pp .

The second line contains mm integers: p1,p2,,pmp_1, p_2, \dots, p_m ( 1pim1 \le p_i \le m ) — the permutation pp .

It is guaranteed that the sum of mm over all test cases does not exceed 31053 \cdot 10^5 .

输出格式

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.

输入输出样例

  • 输入#1

    4
    8
    6 5 7 8 4 3 1 2
    4
    3 1 4 2
    1
    1
    8
    7 8 4 3 1 2 6 5

    输出#1

    4
    -1
    0
    -1

说明/提示

Consider the first test.

In the first test case, you can act like this (the vertex to which the operation is applied at the current step is highlighted in purple):

It can be shown that it is impossible to make a tree beautiful in fewer operations.In the second test case, it can be shown that it is impossible to make a tree beautiful.

In the third test case, the tree is already beautiful.

首页