Permutation and Inversions

4.8

4 votes
Data Structures, Fenwick tree, Medium
Problem

For a permutation P of N numbers, let us define the cyclic shift of P as another permutation Pd such that Pdi = Pi+1 for all i from 1 to N1, and PdN = P1.

We can create N distinct permutations by applying the cyclic shift operation N times.

For an array P of N numbers, let us define the number of inversions in it as the number of pairs (i,j) such that i<j and Pi>Pj.

For each of the N distinct permutations created by applying the cyclic shift operations on the initial permutation, consider it as an array of N numbers and find the number of inversions in it. Print the bitwise XOR of the number of inversions in each newly created permutation.

You need to handle T test cases each containing a new permutation.

Input:

First line of input contains an integer T, denoting the number of test cases. Each test case contains 2 lines. First line of each test case contains a single integer N, denoting the number of elements in the permutation P. Next line of each test case contains N space separated integers denoting the permutation P.

Output:

For each testcase, print an integer, the bitwise XOR of the number of inversions in each permutation which are created by cyclic shifts on the initial permutation.

Constraints:

1T10

1N105

1PiN

Sample Input
1
5
1 5 2 4 3
Sample Output
10
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The 5 distinct permutations are:

[1,5,2,4,3] - Inversions4.

[5,2,4,3,1] - Inversions8.

[2,4,3,1,5] - Inversions4.

[4,3,1,5,2] - Inversions6.

[3,1,5,2,4] - Inversions4.

Final answer =48464=10

Editor Image

?