POJ 2309 BST (lowbit用法)
阿新 • • 發佈:2020-08-13
題目連結: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 }