Chinaunix首页 | 论坛 | 博客
  • 博客访问: 350717
  • 博文数量: 122
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 1191
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 11:12
文章分类

全部博文(122)

文章存档

2010年(122)

我的朋友

分类: C/C++

2010-04-03 18:48:47

一、问题描述

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

 

二、解题思路

看到这个结构,我想起了树状数组里的int Lowbit(int x)函数,这个函数的计算结果是2k,其中kx的二进制数表示的后面连续0的个数。那么2k就是x所管区间的元素个数。比如上图所示,以8为根的子树一共有8个元素(包括它自己)。那么以8为根的子树中最小的数是8-2k+1,问题关键在于求2k。可以通过位来求:

int Lowbit(int x)

{

    return x&(x^(x-1));// return x&(-x);

}

求到最小的数和求最大数就方便了,最小数加最大数的和是x的两倍。

三、代码

 

#include<iostream>
using namespace std;
int Lowbit(int x)
{
    //return x&(x^(x-1));
    return x&(-x);
}
int GetLowest(int x)
{
    return x-Lowbit(x)+1;
}
int main()
{
    int N;
    int i;
    int a;
    cin>>N;
    for(i=0;i<N;++i)
    {
        cin>>a;
        int t=GetLowest(a);
        cout<<t<<" "<<a*2-t<<endl;

    }
    return 0;
}


阅读(1464) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~