描述
如上图所示,由正整数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
本以为是模拟二叉树,没想到是找规律。。。。
AC代码:
#include<iostream>
using namespace std;
int main()
{
int m;
int n;
while (cin>>m>>n&&n&&m)
{
int ans = 0;
if (m==n)
{
ans=1;
}
else
if (m<=n)
{
ans=1;
int l=2*m;
int r=2*m+1;
while (r<n)
{
ans+=r-l+1;
l=2*l;
r=2*r+1;
}
if (n>=l)
ans+=n-l+1;
}
cout<<ans<<endl;
}
return 0;
}
附赠二叉树写法(超时)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m,ans;
struct dian
{
int data;
dian *l;
dian *r;
}*D,*T;
dian *jian(int x)
{
if(x>m)return NULL;
dian *t=new dian;
t->data=x;
t->l=jian(x*2);
t->r=jian(x*2+1);
return t;
}
void zhao(dian *root)
{
if(root==NULL)return;
if(root->data==n)
{
//cout<<root->data<<endl;
T=root;
return ;
}
zhao(root->l);
zhao(root->r);
}
void show(dian *root)
{
if(root==NULL)return;
//cout<<root->data<<endl;
ans++;
show(root->l);
show(root->r);
}
int main()
{
while(cin>>n>>m&&(n+m))
{
ans=0;
D=jian(1);
zhao(D);
//cout<<T->data<<endl;
show(T);
cout<<ans<<endl;
}
}