被一道简单题卡了 个小时,导致场上没时间写 了。
注意到我们可以将本题看作:给你一个序列 ,每次可以任选数列中的一个数 ,然后将 插入 的左侧或右侧,问最终的序列能否得到。具体来说,就是相当于拆分一个当前的叶子并生成两个新的叶子的操作。
对于样例,可以进行操作 。
观察规律,可得有解的判据为:
有且仅有一个。
对于所有非 数 ,记左侧第一个小于它的数 (需存在),右侧第一个小于它的数 (需存在),需要满足 与 中至少有一个为 。
复杂度 。
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define MAXN 200005
int n,a[MAXN],L[MAXN],R[MAXN],st[MAXN],top = 0;
inline void solve(){
scanf("%lld",&n); int cnt0 = 0;
for( int i = 1 ; i <= n ; i ++ ) scanf("%lld",&a[i]),cnt0 += !a[i];
if( cnt0 != 1 ){ puts("NO"); return; }
for( int i = 1 ; i <= n ; i ++ ){
while( top && a[i] < a[st[top]] ) R[st[top]] = i,top --;
st[++top] = i;
} while( top ) R[st[top]] = n + 1,top --;
for( int i = n ; i >= 1 ; i -- ){
while( top && a[i] < a[st[top]] ) L[st[top]] = i,top --;
st[++top] = i;
} while( top ) L[st[top]] = 0,top --;
for( int i = 1 ; i <= n ; i ++ ){
if( !a[i] ) continue;
if( !( L[i] > 0 && a[L[i]] == a[i] - 1 ) && !( R[i] < n + 1 && a[R[i]] == a[i] - 1 ) ){ puts("NO"); return; }
}
puts("YES");
}
signed main(){
int testcase; scanf("%lld",&testcase);
while( testcase -- ) solve();
return 0;
}