Live2D

2022-04-04 集训题解

T2

Description

小 W 的手上有一颗 \(n\) 个节点的二叉搜索树,里面有从 \(1\)\(n\)\(n\) 个数字。(二叉搜索树即为中序遍历恰好为 \(1\)\(n\) 的二叉树)

现在你想知道这棵树的形态。但是小 W 不会直接告诉你,只允许你询问以某个点为根的子树是否恰好包含 \([l,r]\) 中的所有点。

你需要在 \(2\times n\) 次查询之内得到整棵树的形态。

Solution

考虑建立笛卡尔树的步骤,那我们需要做的就是一个点是否在另外一个点的左儿子里面,你发现既然已经当了左儿子,那么里面一定已经构造完了,所以我们只需要判断这个点是否覆盖这个区间即可。

Code

#include<bits/stdc++.h>
#include"interact.h"
using namespace std;

#define Int register int
#define MAXN 105

struct node{
	int x,l;
};
node sta[MAXN];

int lson[MAXN],rson[MAXN];
int getr (int x){
	while (rson[x]) x = rson[x];
	return x;
}

void guess(int n){
	int top = 0;
	for (Int i = 1;i <= n;++ i){
		int l = i;
		while (top && query (sta[top].x,sta[top].l,getr (sta[top].x))) lson[i] = sta[top].x,l = sta[top].l,-- top;
		if (top) rson[sta[top].x] = i;
		sta[++ top] = node{i,l};
	}
	for (Int i = 1;i <= n;++ i){
		if (lson[i]) report (i,lson[i]);
		if (rson[i]) report (i,rson[i]);
	}
}
posted @ 2022-04-04 15:08  Dark_Romance  阅读(68)  评论(1编辑  收藏  举报