Author: | MathModel |
Prepared by: | MathModel |
Edited by: | MathModel |
An operation only ever exchanges two indices of the same parity , so the parity of the index holding a given value never changes , and the multiset of values standing on the odd indices is invariant . Within one parity class , transpositions generate every permutation of that class , so any rearrangement of the odd-indexed values is reachable , and independently so for the even-indexed ones .
So the odd slots and the even slots can be sorted independently , and nothing more can be done : sort the values on the odd indices among themselves , sort the values on the even indices among themselves , put them back in place , and the result is the best arrangement reachable from . The answer is YES if and only if that arrangement is sorted , which happens exactly when p_i \equiv i \pmod 2 for all .
def solve():
n=int(input())
p=list(map(int,input().split()))
odd,even=[],[]
for i in range(0,n,2): odd.append(p[i])
for i in range(1,n,2): even.append(p[i])
odd.sort()
even.sort()
ps=[0]*n
cur=0
for i in range(0,n,2):
ps[i]=odd[cur]
cur+=1
cur=0
for i in range(1,n,2):
ps[i]=even[cur]
cur+=1
if(ps==sorted(ps)):
print("YES")
else:
print("NO")Time complexity: \mathcal{O}(n \log n) per test case . Memory complexity: .