CF1545A.AquaMoon and Strange Sort

题意简述

  每组数据给定一个无序数列,数列中每个数都有一个实时的状态,初始为1。你可以对该数列进行任意次操作,每次操作可以选择数列中任意两个相邻的数进行交换。对于任意一个数,每被交换一次其状态便会被取反。询问对数列进行操作后能否使其变为单调不下降序列,并且最终每个数的状态均为1。

算法概述

  容易发现,若答案为能,则对于任意一个数,交换前后其下标位置的奇偶性不变。

  故对于每一个数值,统计其交换前处于奇数位置的数量与处于偶数位置的数量,然后排序,并统计排序后的数量。将排序前与排序后进行比对即可。

参考代码

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 const int N=1e5+10;
 7 
 8 int a[N];
 9 int odd[N][2],eve[N][2];
10 int n,T;
11 
12 bool judge()
13 {
14     for(int i=1;i<=n;i++)if(odd[a[i]][0]!=odd[a[i]][1]||eve[a[i]][0]!=eve[a[i]][1])return false;
15     return true;
16 }
17 
18 int main()
19 {
20     scanf("%d",&T);
21     while(T--)
22     {
23         scanf("%d",&n);
24         for(int i=1;i<=n;i++)
25         {
26             scanf("%d",&a[i]);
27             if(i&1)odd[a[i]][0]++;
28             else eve[a[i]][0]++;
29         }
30         sort(a+1,a+n+1);
31         for(int i=1;i<=n;i++)
32         {
33             if(i&1)odd[a[i]][1]++;
34             else eve[a[i]][1]++;
35         }
36         if(judge())printf("YES\n");
37         else printf("NO\n");
38         for(int i=1;i<=n;i++)odd[a[i]][0]=odd[a[i]][1]=eve[a[i]][0]=eve[a[i]][1]=0;
39     }
40     return 0;
41 }

 

posted @ 2021-07-12 14:47  魑吻丶殇之玖梦  阅读(83)  评论(0编辑  收藏  举报