poj 2309 BST

来源:互联网 发布:香港gpa算法 编辑:程序博客网 时间:2024/05/23 19:14

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

2810

Sample Output

1 159 11

 

这也是一道很有意思的水题~

我发现第n层上(n=0,1,2……)的数字分别为2^n+2^(n+1)*k~由此就可以计算出每个数所在层数~

而根节点与最大数和最小数之间相差sigma 2^k- (k=0,1,2……n-1)~

所以代码如下~

#include"stdio.h"
int main()
{
 int n;
 int x;
 int i,j;
 int count;
 int lc,rc;
 int s;
 scanf("%d",&n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&x);
  count=0;
  lc=rc=x;
  s=1;
  for(;;)
  {
   if(x%2!=0)
    break;
   x=x/2;
   count++;
  }
     for(j=0;j<count;j++)
  {
   lc=lc-s;
   rc=rc+s;
   s*=2;
  }
  printf("%d %d\n",lc,rc); 
 }
 return 0;
}

带看完discuss之后~我发现更简单的方法~利用树状数组思想中的位运算~

最小值就是该数用二进制表示后将其中的最后一个1挪到最后一位~

最大值就是将最后一个1后面全赋为1~

利用分别利用x-(x&(-x))+1和x+(x&(-x))-1就可以实现~

注意~(-x)表示将x取反后加1~

在位运算中还需注意~符号^是异或的意思~

下面是代码~要简洁许多~

 #include"stdio.h"
int main()
{
 int n;
 int x;
 scanf("%d",&n);
  while(n--)
  {
   scanf("%d",&x);
   printf("%d %d\n",x-(x&(-x))+1,x+(x&(-x))-1);
  }
}

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 干洗出现问题了怎么办 教师工资太低了怎么办 鸽子得了新城疫怎么办 氮肥施多了怎么办 当兵体质差跑步怎么办 手盘核桃脏了怎么办 怀孕吃了巴旦木怎么办 护士证丢了怎么办 扶贫搬迁老房子怎么办 ucl录取差两分怎么办 考研准考证号填错了怎么办? 拿到工伤证后怎么办 专接本有挂科怎么办 小孩发烧后惊厥怎么办 深圳民办学校停办学生怎么办 教育机构不退钱怎么办 智慧树错过选课怎么办 河南城建学院怎么办网 建学校土地手续怎么办 德国预科不能毕业怎么办 想出国打工怎么办手续 终结执行了该怎么办 网银界面打不开怎么办 abr检查结果异常怎么办 大排畸胎儿位置不好怎么办 交社保中途死了怎么办 不知道社保密码怎么办 社保卡没有信息怎么办 医保卡没有信息怎么办 信访局不受理怎么办 没身份证怎么办健康证 海峡银行怎么办医保卡 小学借读生学籍怎么办 光头也有头皮屑怎么办 情侣没话题了怎么办 月经前后有异味怎么办 头发里有湿疹怎么办 公务员退休职业年金怎么办 迅雷打不开怎么办安卓 苹果迅雷闪退怎么办 青羊区爱君家政欺骗学员怎么办