题解 - [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
3
2
8
10

Sample Output

1
2
1 15
9 11

Source

POJ Monthly,Minkerui

题意简述

给出 \(x\), 输出在满二叉搜索树 (如下图) 中,以 \(x\) 为根的子树中的最小结点编号和最大结点编号

解题思路

在上图中随便找几个例子就能发现

  • 最小结点编号即为根编号对应二进制位中将最低位的 1 换为 0+1 的值

    如: 12 -> 110010 -> 1010, 对应的最小结点编号均为 9 -> 1001

  • 最大结点编号即为根编号对应二进制位中将最低位的 1 后面的 0 全部变为 1 的值

    如: 12 -> 110014 -> 1110, 对应的最大结点编号均为 15 -> 1111

证明是很容易的

对于取最低位 1, 有一个运算想必是我们非常熟悉的,就是 lowbit(x), 答案和它密切相关

设给定结点编号为 x, 则

  • 最小结点编号即为 x - lowbit(x) + 1
  • 最大结点编号即为 x + lowbit(x) - 1

代码参考

Show code

POJ_2309view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
* @Author: Tifa
* @Description: From <https://github.com/Tiphereth-A/CP-archives>
* !!! ATTENEION: All the context below is licensed under a
* GNU Affero General Public License, Version 3.
* See <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
#include <cstdio>
#define lowbit(x) ((x) & (-x))
int main() {
int kase;
scanf("%d", &kase);
while (kase--) {
int k;
scanf("%d", &k);
printf("%d %d\n", k - lowbit(k) + 1, k + lowbit(k) - 1);
}
}