跳到正文

题解

CF1919D 01 Tree

MaxBlazeResFire约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年1月7日
收录
2025年12月12日
更新
2026年9月14日
篇幅
约 3 分钟
题目
CF1919D

版本

  1. v1当前

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

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

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

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

1.1. 00 有且仅有一个。

2.2. 对于所有非 00 数 aia_i,记左侧第一个小于它的数 aLia_{L_i}(需存在),右侧第一个小于它的数 aRia_{R_i}(需存在),需要满足 aLia_{L_i} 与 aRia_{R_i} 中至少有一个为 ai−1a_i-1。

复杂度 O(n)O(n)。

C++
#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;
}