775 字
4 分钟
MEX-Reordering

题面#

You are given an integer array aa consisting of nn elements. Denote f(l,r)=MEX([al,al+1,,ar])f(l, r) = \operatorname{MEX}([a_l, a_{l + 1}, \ldots, a_r]) ^{\text{∗}}.

Determine if there is a way to reorder the array aa such that for every ii (1in11 \le i \le n - 1), f(1,i)f(i+1,n)f(1, i) \neq f(i + 1, n). In other words, for every split point ii, the MEX\operatorname{MEX} of the prefix must be different from the MEX\operatorname{MEX} of the suffix.

^{\text{∗}}The minimum excluded (MEX) of a collection of integers c1,c2,,ckc_1, c_2, \ldots, c_k is defined as the smallest non-negative integer xx which does not occur in the collection cc.

Input

Each test contains multiple test cases. The first line contains the number of test cases tt (1t5001 \le t \le 500). The description of the test cases follows.

The first line of each test case contains a single integer nn (2n1002 \le n \le 100) — the length of the array.

The second line of each test case contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (0ain0 \le a_i \le n).

Output

Output “YES” if you can reorder aa so that the condition from the statement is satisfied, and “NO” otherwise. You can output the answer in any case (upper or lower). For example, the strings “yEs”, “yes”, “Yes”, and “YES” will be recognized as positive responses.

思路#

先理解 MEX 的含义

MEX 是最小没有出现的非负整数

例如 MEX([1,2,3])=0\operatorname{MEX}([1,2,3])=0

例如 MEX([0,2,4])=1\operatorname{MEX}([0,2,4])=1

例如 MEX([0,1,3])=2\operatorname{MEX}([0,1,3])=2

本题要重排数组,使得对每个切分点 i(1in1)i\,(1\le i\le n-1) 都满足

MEX(a1,,ai)MEX(ai+1,,an)\operatorname{MEX}(a_1,\ldots,a_i)\ne \operatorname{MEX}(a_{i+1},\ldots,a_n)

关键观察

MEX 是否等于 0011 只取决于 0011 有没有出现

如果一段里没有 00,那么这一段的 MEX 一定是 00

如果一段里有 00 但没有 11,那么这一段的 MEX 一定是 11

如果一段里同时有 0011,那么这一段的 MEX 至少是 22

因此只需要统计数组里 00 的个数 cnt0\text{cnt0}11 的个数 cnt1\text{cnt1} 就能判定答案

分情况讨论

  • 情况一 cnt0=0\text{cnt0}=0

无论怎么重排,任意前缀和后缀都不包含 00,因此它们的 MEX 都是 00,一定会出现相等

答案是 NO

  • 情况二 cnt0=1\text{cnt0}=1

把唯一的 00 放到最后一个位置即可

此时对任意 i<ni<n,前缀不含 00,所以前缀 MEX 为 00,而后缀一定包含这个 00,所以后缀 MEX 大于 00,两边永远不可能相等

答案是 YES

  • 情况三 cnt02\text{cnt0}\ge 2

如果 cnt1=0\text{cnt1}=0

只要一段里出现了 00,由于没有 11,这段的 MEX 就会变成 11;不管怎么重排,总能找到一个切分点让左右两边都至少有一个 00,此时前缀 MEX 和后缀 MEX 都是 11,违反条件

答案是 NO

如果 cnt1>0\text{cnt1}>0

可以构造一种重排来保证所有切分点都不相等

把所有 00 放在数组末尾,并确保至少一个 11 在这些 00 的前面

切在第一个 00 之前时,前缀不含 00,所以前缀 MEX 为 00

后缀含 00,所以后缀 MEX 不会是 00

切在 00 区间内部或之后时,后缀会变成只包含若干个 00 的集合,后缀 MEX 为 11

而前缀因为已经包含 001100 之前,所以前缀同时包含 0011,前缀 MEX 至少为 22

因此两边仍然不相等

答案是 YES

综上

只有两种情况输出 NO

  • cnt0=0\text{cnt0}=0
  • cnt1=0\text{cnt1}=0cnt02\text{cnt0}\ge 2

其余情况全部输出 YES

时间复杂度为 O(n)O(n),只需要一次遍历统计即可

MEX-Reordering
https://github.com/posts/mex-reordering/
作者
FZSGBall
发布于
2026-05-06
许可协议
CC BY-NC-SA 4.0