题目大意:有多组测试数据,每组测试数据为一个长度为n的正整数数组。问是否可以通过任意此特定操作(每次操作可以选择挨着的一个为奇数,一个为偶数的两个数交换)使数组变为不严格的升序数组。如果可以的话输出“YES”,否则输出“NO”。
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an array a1,a2,…,ana1,a2,…,an. You can perform operations on the array. In each operation you can choose an integer ii (1≤i<n1≤i<n), and swap elements aiai and ai+1ai+1 of the array, if ai+ai+1ai+ai+1 is odd.
Determine whether it can be sorted in non-decreasing order using this operation any number of times.
Input
Each test contains multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the length of the array.
The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — the elements of the array.
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, print "Yes" or "No" depending on whether you can or can not sort the given array.
You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Example
input
Copy
4 4 1 6 31 14 2 4 2 5 2 9 6 7 10 3 6 6 6
output
Copy
Yes No No Yes
Note
In the first test case, we can simply swap 3131 and 1414 (31+14=4531+14=45 which is odd) and obtain the non-decreasing array [1,6,14,31][1,6,14,31].
In the second test case, the only way we could sort the array is by swapping 44 and 22, but this is impossible, since their sum 4+2=64+2=6 is even.
In the third test case, there is no way to make the array non-decreasing.
In the fourth test case, the array is already non-decreasing.
解题思路:由于挨着的两个数必须一奇一偶才能交换,得出偶数相连和奇数相连的情况是不可以进行交换。所以可以把数组中的元素分为奇数和偶数两个部分。可以发现,如果奇数数组中或是偶数数组中有逆序的情况,是无法通过题目中的特定操作来把数组变为不严格的升序数组的。
#include<iostream>
using namespace std;
const int N =1e5+10;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int a[N],b[N];
int aa=0,bb=0;
for(int i=0;i<n;i++)
{
int x;
scanf("%d",&x);
if(x%2!=0) a[aa++]=x;
else b[bb++]=x;
}
int f=1;
for(int i=0;i<aa-1;i++)
{
if(a[i]>a[i+1])
{
f=0;
break;
}
}
for(int i=0;i<bb-1;i++)
{
if(b[i]>b[i+1])
{
f=0;
break;
}
}
if(f==1) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}