Petya has an array of integers a1,a2,…,an. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3pairwise distinct indices i, j, and k (1≤i,j,k≤n) and apply i→j→k→i cycle to the array a. It simultaneously places ai on position j, aj on position k, and ak on position i, without changing any other element.
For example, if a is [10,50,20,30,40,60] and he chooses i=2,j=1,k=5, then the array becomes [50,40,20,30,10,60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤5⋅105). Description of the test cases follows.
The first line of each test case contains a single integer n (1≤n≤5⋅105) — the length of the array a.
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n).
It is guaranteed that the sum of nnn over all test cases does not exceed 5⋅105.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
In the 6-th test case Petya can use the 3-cycle 1→3→2→1 to sort the array.
In the 7-th test case Petya can apply 1→3→2→1 and make a=[1,4,2,3]. Then he can apply 2→4→3→2 and finally sort the array.
2. 题解
分析
根据置换群相关的知识可知:
任一一个 m-cycle 的置换都可以改写成 m−1 个 2-cycle 的置换。
以 (3,1,2) 为例:在右结合的情况下 (3,1,2)=(1,3)(2,3)。因此,数组 a 通过 3-cycle 的置换能够变成单调递增,则等价于数组 a 通过偶数次 2-cycle 的置换能变成单调递增。
这里需要注意的一点是,题目没有说数组 a 中的元素是各不相同的,因此需要考虑到有相同元素的情况。一旦出现相同元素,则总是能够通过偶数次 2-cycle 的置换将数组 a 变成单调递增的。比如 [2,2,3] 经过置换 (1,2)(2,3) 变成 [2,3,2],即一旦出现相同元素,则可以一步一步移动任一一个元素,最终实现数组 a 有序。
对于数组 a 中元素各不相同的情况,有两种思路:
一种想法是计算数组 a 的逆序数。因为每做一次 2-cycle 的置换,逆序数就会 ±1。因此,通过偶数次 2-cycle 的置换不会改变数组 a 的逆序数的奇偶性。所以只需要计算数组 a 的逆序数,然后判其奇偶性即可。计算一个数组的逆序数的最优算法有:树状数组(BIT)、CDQ 分治,时间复杂度为 O(nlogn)。
另一种想法则是直接计算数组 a 变成有序所需要的 2-cycle 置换次数。假定数组 a 变成有序后应该满足 ai=i,即数值要等于其对应的下标。然后我们从 ai 开始 BFS,按照 ai→aai→⋯,直到循环回 ai 为止,设整个循环长度为 m,则这个循环即为 m-cycle 的置换,可转换成 m−1 个 2-cycle 的置换。同时我们将访问过的 ai 全部标记上。最终,只需从头到尾遍历一遍数组 a 即可,对每个元素作以下判断: