D. Yet Another Sorting Problem
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Petya has an array of integers a1,a2,…,ana1,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 33-cycles. More formally, in one operation he can pick 33 pairwise distinct indices ii, jj, and kk (1≤i,j,k≤n1≤i,j,k≤n) and apply i→j→k→ii→j→k→i cycle to the array aa. It simultaneously places aiai on position jj, ajaj on position kk, and akak on position ii, without changing any other element.
For example, if aa is [10,50,20,30,40,60][10,50,20,30,40,60] and he chooses i=2i=2, j=1j=1, k=5k=5, then the array becomes [50–––,40–––,20,30,10–––,60][50_,40_,20,30,10_,60].
Petya can apply arbitrary number of 33-cycles (possibly, zero). You are to determine if Petya can sort his array aa, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤5⋅1051≤t≤5⋅105). Description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤5⋅1051≤n≤5⋅105) — the length of the array aa.
The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n).
It is guaranteed that the sum of nn over all test cases does not exceed 5⋅1055⋅105.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array aa using 33-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
先附上:
定义:降序次数为偶数的排列为偶排列;降序次数为奇数的排列为奇排列。
例如排列(2,3,1):从左往右看,2与其后元素相比有降序,即2大于1;3与其后元素相比有降序,即3大于1;1无降序;则排列降序次数为2次,因此为偶排列。
例如排列(1,3,2):从左往右看,1与其元素无降序,3与其后元素有降序,2无降序;因此其排列降序次数为1,为奇排列。
这题比赛时完全没思路,看了大佬的题解知道了什么是奇排序,偶排序。题目这种规则从这里下手会发现题目是成对改变的,也就是偶排序,一次改变会将会将逆序对的数量变化2,所以只要判断逆序对的个数是否为偶数就行,当然当有两个或以上的个数相同就能任意改变奇偶性,这种情况总是可以的。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
#define ll long long
#define PII pair<ll, int>
#define x first
#define y second
const int N = 1e6 + 6;
const int mod = 1e9 + 7;
int a[N], c[N];
int tr[N];
int lowbit(int x) {
return x & -x;
}
int sum(int x) {
int res = 0;
for (int i = x; i; i -= lowbit(i)) res += tr[i];
return res;
}
void add(int x, int n) {
for (int i = x; i <= n; i += lowbit(i)) tr[i] ++;
}
void solve() {
int n;
cin >> n;
memset(c, 0, (n + 2) * sizeof(int));
memset(tr, 0, (n + 2) * sizeof(int));
int maxx = 1;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), c[a[i]]++, maxx = max(c[a[i]], maxx);
if (maxx >= 2) {
puts("YES");
return;
}
int res = 0;
for (int i = 1; i <= n; i++) {
res += sum(n) - sum(a[i]);
add(a[i], n);
}
if (res & 1) puts("NO");
else puts("YES");
}
int main(){
int t;
cin >> t;
while (t--) solve();
return 0;
}