Larry's Array
by nikasvanidze
Larry has a permutation of numbers, , whose unique elements range from to (i.e.: ). He wants 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 consecutive indices and rotate their elements in such a way that rotates to , which rotates to , which rotates back to .
For example: if and the robot rotates , becomes .
On a new line for each test case, print if the robot can fully sort ; otherwise, print .
Input Format
The first line contains an integer, , the number of test cases.
The subsequent lines each describe a test case over lines:
The subsequent lines each describe a test case over lines:
- An integer, , denoting the size of .
- space-separated integers describing , where the value describes element .
Constraints
Output Format
On a new line for each test case, print if the robot can fully sort ; otherwise, print .
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 (size of ) number of pairs,
where and .
Let's prove that parity of inversions will not change:
-> .
Order of changed thats .
Order of changed thats .
So change is or or .
Prove that we can always get permutation:
or . ( and are swapped). using out operation we are moving and left by one, in this way we can move in first place, then move to second place and so on including .
So, number of inversions will be or .
If it is then it's impossible to sort, and if it's 0 that means it's sorted.
Calculate parity using any BST, solution will be .
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;
}