Monday 21 March 2016

Larry has a permutation of N numbers, A, whose unique elements range from 1 to N (i.e.: A={a1,a2,,aN1,aN}). He wants A to be sorted, so he delegates the task of doing so to his robot. The robot can perform the following operation as many times as it wants:
  • Choose any 3 consecutive indices and rotate their elements in such a way that ABCrotates to BCA, which rotates to CAB, which rotates back to ABC.
For example: if A={1,6,5,2,4,3} and the robot rotates (6,5,2)A becomes {1,5, 2, 6,4,3}.
On a new line for each test case, print YES if the robot can fully sort A; otherwise, print NO.
Input Format
The first line contains an integer, T, the number of test cases. 
The 2T subsequent lines each describe a test case over 2 lines:
  1. An integer, N, denoting the size of A.
  2. N space-separated integers describing A, where the ith value describes element ai.
Constraints
  • 1T10
  • 3N1000
  • 1aiN, where every element ai is unique.
Output Format
On a new line for each test case, print YES if the robot can fully sort A; otherwise, print NO.
Sample Input
3
3
3 1 2
4
1 3 4 2
5
1 2 3 5 4
Sample Output
YES
YES
NO
Let's call inversion in sequence A (size of N) number of pairs(x,y), where 1x<yN and Ax>Ay.
Let's prove that parity of inversions will not change: A,B,C -> B,C,A. Order of A,C changed thats ±1. Order of A,B changed thats ±1. So change is 2 or 0 or 2. Prove that we can always get permutation: [1,2,3,...,n2,n1,n] or [1,2,3,...,n2,n,n1]. (n and n1 are swapped). using out operation we are moving B and C left by one, in this way we can move 1 in first place, then move 2 to second place and so on including n2. So, number of inversions will be 0([1,2,3,...,n2,n1,n]) or 1([1,2,3,...,n2,n,n1]). If it is 1 then it's impossible to sort, and if it's 0 that means it's sorted.
Calculate parity using any BST, solution will be O(TNlog2N).
In this problem you can calculate answer by compairing each pair. 
#include<bits/stdc++.h>
using namespace std;
int a[1010];
int main()
{
  int n;
  int t;
  cin>>t;
  while(t--)
  {
    
     cin>>n;
     for(int i=1;i<=n;i++)
     cin>>a[i];
     int in=0;
     for(int i=1;i<=n;i++)
     {
        for(int j=i+1;j<=n;j++)
 {
      if(a[j]<a[i])
  in++;
 }
}
if(in&1)
cout<<"NO"<<endl;
else cout<<"YES"<<endl;
  }
  return 0;
}