CF1741D Masha and a Beautiful Tree
题目描述
Masha 在森林中散步,发现了一棵高度为 $n$ 的满二叉树,以及一个长度为 $m=2^n$ 的排列 $p$。
高度为 $n$ 的满二叉树是一棵有根树,其中除了叶子结点外,每个结点恰好有两个儿子,并且从根结点到任意一个叶子结点的路径长度都是 $n$。
如果一棵树叶子上的值从左到右按升序排列,玛莎就认为这棵树是**美丽的**。
在一次操作中,玛莎可以选择树上的任意一个非叶子结点,并交换它的左儿子和右儿子(连同它们的子树一起交换)。
请帮助玛莎判断她是否能够通过若干次操作让一棵树变得美丽。如果可以,输出使树变得美丽所需的**最少操作次数**。
输入格式
第一行,一个正整数 $t(1 \leq t \leq 10^4)$,表示数据组数。
每组输入由两行组成:
第一行是一个正整数 $m(1 \leq m \leq 262144)$,表示树的叶子结点的个数。
第二行,$m$ 个正整数,表示每个叶子节点上的正整数。
数据保证 $\sum m \leq 3 \times 10^5$,且 $m$ 一定为 $2$ 的整数幂。
输出格式
对于每一组数据,输出一个正整数,表示最小的交换次数,或者输出一个 $-1$——如果无论怎么交换都不能使从左往右数的第 $i$ 个叶子结点上的正整数为 $i$ 。
(Translated by @[chinazhanghaoxun](https://www.luogu.com.cn/user/684848))
说明/提示
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.