TLE代码:
(O(N^2))
#include<bits/stdc++.h>
using namespace std;
int n,b[100005],pl;
bool v[100005];
struct node{
int num;
int x;
}a[100005];
bool cmp(node a,node b){
return a.x<=b.x;
}
int main(){
int t;
cin>>t;
while(t--){
pl=1;
bool flag=1;
memset(v,0,sizeof(v));
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].x;
b[i]=a[i].x;
a[i].num=i;
}
sort(b+1,b+1+n);
sort(a+1,a+1+n,cmp);
int tl;
for(int i=1;i<=n;i++){
while(v[pl]==1&&pl<=n) pl++;
if(pl>n){
flag=0;
break;
}
tl=pl;
while(abs(tl-a[i].num)%2==1&&b[tl]==a[i].x)
tl++;
if(b[tl]==a[i].x&&abs(tl-a[i].num)%2==0){
v[tl]=1;
}
else{
flag=0;
break;
}
}
if(flag) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
AC代码:
(O(N))
#include<bits/stdc++.h>
using namespace std;
int n,a[100005];
bool v[100005];
int even[100005],odd[100005];
int main(){
int t;
cin>>t;
while(t--){
memset(even,0,sizeof(even));
memset(odd,0,sizeof(odd));
bool flag=1;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
if(i%2==1) even[a[i]]++;
else odd[a[i]]++;
}
sort(a+1,a+1+n);
for(int i=1;i<=n;i++){
if(i%2==1){
if(even[a[i]]) even[a[i]]--;
else{
flag=0;
break;
}
}
else{
if(odd[a[i]]) odd[a[i]]--;
else{
flag=0;
break;
}
}
}
if(flag) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}