版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
title: "题解 - [POJ 2309] BST" categories:
Consider an infinite full binary search tree (see the figure below), the numbers in the nodes are 1, 2, 3, .... In a subtree whose root node is X, we can get the minimum number in this subtree by repeating going down the left node until the last level, and we can also find the maximum number by going down the right node. Now you are given some queries as "What are the minimum and maximum numbers in the subtree whose root node is X?" Please try to find answers for there queries
In the input, the first line contains an integer N, which represents the number of queries. In the next N lines, each contains a number representing a subtree with root number X ($1 \leqslant X \leqslant 2^{31} - 1$)
There are N lines in total, the i-th of which contains the answer for the i-th query
2
8
10
1 15
9 11
POJ Monthly,Minkerui
给出 $x$, 输出在满二叉搜索树(如下图)中, 以 $x$ 为根的子树中的最小结点编号和最大结点编号
在上图中随便找几个例子就能发现
最小结点编号即为根编号对应二进制位中将最低位的1
换为0
后+1
的值
如: 12 -> 1100
和 10 -> 1010
, 对应的最小结点编号均为 9 -> 1001
最大结点编号即为根编号对应二进制位中将最低位的1
后面的0
全部变为1
的值
如: 12 -> 1100
和 14 -> 1110
, 对应的最大结点编号均为 15 -> 1111
证明是很容易的
对于取最低位1
, 有一个运算想必是我们非常熟悉的, 就是lowbit(x)
, 答案和它密切相关
设给定结点编号为x
, 则
x - lowbit(x) + 1
x + lowbit(x) - 1