题目1113:二叉树
时间限制:1 秒
内存限制:32 兆
特殊判题:否
提交:2599
解决:778
-
题目描述:
如上所示,由正整数1,2,3……组成了一颗特殊二叉树。我们已知这个二叉树的最后一个结点是n。现在的问题是,结点m所在的子树中一共包括多少个结点。
-
比如,n = 12,m = 3那么上图中的结点13,14,15以及后面的结点都是不存在的,结点m所在子树中包括的结点有3,6,7,12,因此结点m的所在子树中共有4个结点。
-
输入数据包括多行,每行给出一组测试数据,包括两个整数m,n (1 <= m <= n <= 1000000000)。最后一组测试数据中包括两个0,表示输入的结束,这组数据不用处理。
-
对于每一组测试数据,输出一行,该行包含一个整数,给出结点m所在子树中包括的结点的数目。
-
3 12
-
0 0
-
4
-
输入:
-
输出:
-
样例输入:
-
样例输出:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <math.h>
using namespace std;
int main()
{
int m,n;
int i,_h;
int count0;
int left,right;
while(scanf("%d %d",&m,&n)==2&&m!=0)
{
_h=(int)(log(n)/log(2)+1)-(int)(log(m)/log(2)+1);
left=right=m;
count0=0;
count0+=(int)pow(2,_h)-1;
for(i=0; i<_h; i++)
{
left=left*2;
right=right*2+1;
}
if(i==0)//如果m、n在同一层
count0=1;
else
{
if(left<=n)
count0+=n-left+1;
else if(right<=n)
count0+=right-left+1;
}
printf("%d\n",count0);
}
return 0;
}