#P10370. 「LAOI-4」Mex Tower (Hard ver.)

「LAOI-4」Mex Tower (Hard ver.)

Background

The difference from the Easy Version is that this problem requires checking whether the solution is valid.

It is guaranteed that for all test points in this problem, the time and memory limits are at least 2.52.5 times those of the standard solution (std).

Problem Description

Define mex(x,y)\operatorname{mex}(x, y) as the smallest non-negative integer that does not appear in the set {x,y}\{x, y\}. For example, mex(1,5)=0\operatorname{mex}(1, 5) = 0, and mex(3,0)=1\operatorname{mex}(3, 0) = 1.

Next, we define one operation on a non-negative integer sequence a1ana_1 \dots a_n as replacing sequence aa with a sequence a1an1a'_1 \dots a'_{n-1} of length n1\bm{n - 1}, where ai=mex(ai,ai+1)a'_i = \operatorname{mex}(a_i, a_{i+1}).

Given an integer sequence a1ana_1 \dots a_n of length nn, where 0ai1090 \leq a_i \leq 10^9, perform the operation n1n - 1 times in order. Obviously, the final sequence aa will contain only one number. Define the value of this final number as the value of the sequence, denoted by f(a)f(a).

For the given nn and sequence aa, determine whether for all non-negative integer sequences bb of length nn, it holds that f(a)f(b)f(a) \ge f(b).

Input Format

This problem contains multiple test cases.

The first line contains a positive integer TT, the number of test cases.

For each test case, the first line contains a positive integer nn.

The next line contains nn integers, representing the sequence aa.

Output Format

For each test case, output one string per line: Yes or No.

2
2
0 1
3
1 0 2
Yes
No

Hint

Sample Explanation

For n=2n = 2, f(a)=2f(a)=2. It can be proven that for all sequences bb of length 22, f(b)2f(b)\le 2.

For n=3n = 3, f(a)=0f(a)=0. There exists a sequence b=[114,514,1919]b=[114,514,1919] with f(b)=1>0f(b)=1>0.

Constraints

"This problem uses bundled tests."

Subtask\text{Subtask} n\sum n \le Special Property Total Score
11 10310^3 None 1010
22 51055\cdot 10^5 A\text{A} 55
33 B\text{B} 1010
44 ai<2a_i< 2 1515
55 10610^6 None 2020
66 31063\cdot 10^6 4040

Special Property A\text{A}: It is guaranteed that ai=ia_i=i.

Special Property B\text{B}: It is guaranteed that ai=imod3a_i=i\bmod 3.

For all testdata, it is guaranteed that 1T1041 \leq T \leq 10^4, n>1n > 1, and n3106\sum n \leq 3\cdot 10^6.

Translated by ChatGPT 5