2309 BST

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 <= 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

2
8
10

Sample Output

1 15
9 11


很有意思的一道题,我在纸上画了一下题目中BST的树状数组找出了规律,不得不说它真的挺神奇。对于一个子树根x,它的左子树是它覆盖的区间,最小值即为区间的最左端;右子树是覆盖它的区间,最大值即为区间的第二最右端,最右端是x的根。关键还是lowbit()这个运算

#include <iostream>
#include <cstdio>
#define lowbit(i) (i & (-i))

using namespace std;

int main()
{
    int n, x;
    scanf("%d", &n);
    while(n--)
    {
        scanf("%d", &x);
        int l = x - lowbit(x) + 1;
        long long r = x + lowbit(x) - 1;
        printf("%d %lld\n", l, r);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BST(Binary Search Tree)是一种常见的搜索数据结构,它具有以下特点: - 每个节点最多有两个子节点:左子节点和右子节点。 - 左子节点的值小于等于父节点的值,右子节点的值大于父节点的值。 - 对于每个节点,其左子树和右子树都是二叉搜索树。 以下是一个用Python实现的BST示例: ```python class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): if self.root is None: self.root = Node(value) else: self._insert_recursive(self.root, value) def _insert_recursive(self, node, value): if value < node.value: if node.left is None: node.left = Node(value) else: self._insert_recursive(node.left, value) else: if node.right is None: node.right = Node(value) else: self._insert_recursive(node.right, value) def search(self, value): return self._search_recursive(self.root, value) def _search_recursive(self, node, value): if node is None or node.value == value: return node elif value < node.value: return self._search_recursive(node.left, value) else: return self._search_recursive(node.right, value) ``` 你可以使用该BST类来创建一个二叉搜索树,并进行插入和搜索操作。例如: ```python bst = BST() bst.insert(5) bst.insert(3) bst.insert(7) bst.insert(1) bst.insert(4) print(bst.search(3)) # 输出: <__main__.Node object at 0x...> ``` 希望以上代码能帮到你!如果有任何疑问,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值