CF1741D Masha and a Beautiful Tree

题目描述

Masha 在森林里散步时发现了一棵深度为 $n$ 的满二叉树,它有 $m = 2^n$ 个叶子结点,每个叶子节点上都有一个正整数 $p_i$。 Masha 希望交换一些子树之后可以使从左往右数的第 $i$ 个叶子结点上的正整数为 $i$(因为她觉得这样的一棵满二叉树很漂亮)。你需要帮她找到最少需要交换的次数。

输入格式

第一行,一个正整数 $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 @[owo_ImposterAnYu_owo](https://www.luogu.com.cn/user/510555))

说明/提示

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): ![](https://cdn.luogu.com.cn/upload/vjudge_pic/CF1741D/fccb66d1ee69615b7d772fe2121bf7c21db1b0ee.png)![](https://cdn.luogu.com.cn/upload/vjudge_pic/CF1741D/8842b319e5cad677d6c155ee82d1758b0ed2c5b1.png)![](https://cdn.luogu.com.cn/upload/vjudge_pic/CF1741D/014d05850f0c2fd08d1e624e02c8dac0c1c49ab4.png)![](https://cdn.luogu.com.cn/upload/vjudge_pic/CF1741D/6fe4b73e71d9433e744ffa75181ad32c3a2c7646.png) 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.