题解 - [POJ 2309] BST
原始题面
Description
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
Input
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\))
Output
There are N lines in total, the i-th of which contains the answer for the i-th query
Sample Input
1 | 2 |
Sample Output
1 | 1 15 |
Source
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
代码参考
Show code
1 | /* |