题面
You are given an integer array consisting of elements. Denote .
Determine if there is a way to reorder the array such that for every (), . In other words, for every split point , the of the prefix must be different from the of the suffix.
The minimum excluded (MEX) of a collection of integers is defined as the smallest non-negative integer which does not occur in the collection .
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
The first line of each test case contains a single integer () — the length of the array.
The second line of each test case contains integers ().
Output
Output “YES” if you can reorder 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 是否等于 或 只取决于 和 有没有出现
如果一段里没有 ,那么这一段的 MEX 一定是
如果一段里有 但没有 ,那么这一段的 MEX 一定是
如果一段里同时有 和 ,那么这一段的 MEX 至少是
因此只需要统计数组里 的个数 和 的个数 就能判定答案
分情况讨论
- 情况一
无论怎么重排,任意前缀和后缀都不包含 ,因此它们的 MEX 都是 ,一定会出现相等
答案是 NO
- 情况二
把唯一的 放到最后一个位置即可
此时对任意 ,前缀不含 ,所以前缀 MEX 为 ,而后缀一定包含这个 ,所以后缀 MEX 大于 ,两边永远不可能相等
答案是 YES
- 情况三
如果
只要一段里出现了 ,由于没有 ,这段的 MEX 就会变成 ;不管怎么重排,总能找到一个切分点让左右两边都至少有一个 ,此时前缀 MEX 和后缀 MEX 都是 ,违反条件
答案是 NO
如果
可以构造一种重排来保证所有切分点都不相等
把所有 放在数组末尾,并确保至少一个 在这些 的前面
切在第一个 之前时,前缀不含 ,所以前缀 MEX 为
后缀含 ,所以后缀 MEX 不会是
切在 区间内部或之后时,后缀会变成只包含若干个 的集合,后缀 MEX 为
而前缀因为已经包含 且 在 之前,所以前缀同时包含 和 ,前缀 MEX 至少为
因此两边仍然不相等
答案是 YES
综上
只有两种情况输出 NO:
- 且
其余情况全部输出 YES
时间复杂度为 ,只需要一次遍历统计即可