vjudge submit link
Topic: Binary Tree
如上图所示,由正整数1,2,3……组成了一颗二叉树。
我们已知这个二树的最后一个结点是n。
现在的问题是,结点m所在的子树中一共包括多少个结点。
比如,n = 12,m = 3那么上图中的结点13,14,15以及后面的结点
都是不存在的,结点m所在子树中包括的结点有3,6,7,12,
因此结点m的所在子树中共有4个结点。
Input
输入数据包括多行,每行给出一组测试数据,包括两个整数m,n
(1 <= m <= n <= 1000000000)。
最后一组测试数据中包括两个0,表示输入的结束,这组数据不用处理。
Output
对于每一组测试数据,输出一行,该行包含一个整数,
给出结点m所在子树中包括的结点的数目。
Sample Input
3 12
0 0
Sample Output
4
Problem-solving ideas:
Thinking question: Find how many layers meet the conditions at node m and below, and then use the geometric sequence formula to calculate. For those who are dissatisfied with the last layer, calculate separately, and then calculate the total.
Code
#include<stdio.h>
#include<math.h>
int main()
{
int m,n;
while(~scanf("%d %d",&m,&n))
{
if(n==0&&m==0)
break;
int depth=1;//代表:结点m及以下满二叉树的深度。
int L,R;//L,R分别代表当前该层的左右最大区间(结点m为根结点)
L=R=m;
while(1)
{
L=L*2;
R=R*2+1;//当前层的下一层的右区间
if(R>n)
break;
depth++;
}
int sum=pow(2,depth)-1;
if(n>=L)//最后一层的结点数
sum+=(n-L+1);
printf("%d\n",sum);
}
return 0;
}