CF1919D 01 Tree

· · 题解

被一道简单题卡了 2 个小时,导致场上没时间写 \rm F1 了。

注意到我们可以将本题看作:给你一个序列 [0],每次可以任选数列中的一个数 x,然后将 x+1 插入 x 的左侧或右侧,问最终的序列能否得到。具体来说,就是相当于拆分一个当前的叶子并生成两个新的叶子的操作。

对于样例,可以进行操作 [0]\rightarrow[0,1]\rightarrow[1,0,1]\rightarrow[1,0,1,1]\rightarrow[2,1,0,1,1]。

观察规律,可得有解的判据为:

$2.$ 对于所有非 $0$ 数 $a_i$,记左侧第一个小于它的数 $a_{L_i}$(需存在),右侧第一个小于它的数 $a_{R_i}$(需存在),需要满足 $a_{L_i}$ 与 $a_{R_i}$ 中至少有一个为 $a_i-1$。 复杂度 $O(n)$。 ```cpp #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; } ```