POJ 2309 BST (lowbit用法)

题目链接:POJ 2309

Describe:
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 <= X <= 231 - 1).
Output:
There are N lines in total, the i-th of which contains the answer for the i-th query.
Sample Input:
2
8
10
Sample Output:
1 15
9 11

题目大意:

给一个满二叉树的节点,问以该节点为根的满二叉树的最大值和最小值。

解题思路:

顺便学习满二叉树的性质:

某个数x之后的层数为二进制最右边1的位置(有无想到lowbit函数)

满二叉树节点数:2^k-1(k为层数)

输入一个数x,得到该数二进制最右1的位置,假设为m,则以x为根的满二叉树的左子树的范围为[min,x-1],右子树的范围为[x+1,max],并且,节点数为2^m-1,所以:

1、x-1-min+1 = (2^m-1-1)/2 - 1 = lowbit(x) - 1

2、max-(x+1)+1 = (2^m-1-1)/2

所以 min = x-lowbit(x)+1     max = x+lowbit(x)-1

AC代码:

 1 #include <iostream>
 2 using namespace std;
 3 int lowbit(int x)
 4 {
 5     return x&(-x);
 6 }
 7 int main()
 8 {
 9     int n;
10     cin >> n;
11     while(n--)
12     {
13         int x;
14         cin >> x;
15         cout << x-lowbit(x)+1 << " " << x+lowbit(x)-1 << endl;
16     }
17     return 0;
18 }

 

posted @ 2020-08-13 13:24  不敢说的梦  阅读(122)  评论(0)    收藏  举报