题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2882
5 1 2 2 3 4 3 1024 2048 3214567 9998877
1 2 3 1 44
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=99999;
int f[maxn];
int len;
void init()//初始化,画出满二叉树
{
f[0]=1;
for(int i=1;;i++)
{
f[i]=f[i-1]*2;
if(f[i]>1e9)
{
len=i-1;
break;
}
}
}
int main()
{
init();
//cout<<"len"<<len<<endl;
int t;
cin>>t;
while(t--)
{
int a,b;
int step=0;
cin>>a>>b;
if(a>b)
swap(a,b);//用b代表较大的数
int pos; //pos代表较小的数所在层
for(int i=0;i<len;i++)
{
if(a>=f[i]&&a<f[i+1])//求出较小的数所在的层数
{
pos=i;
break;
}
}
while(1)
{
if(b>=f[pos]&&b<f[pos+1]) //较大的数往上跳,直到与较小的数在同一层
break;
else
{
b/=2;
step++;
}
}
while(a!=b)
{
b/=2; //然后两个数一起往上跳
a/=2;
step+=2;
}
cout<<step<<endl;
}
return 0;
}原文地址:http://blog.csdn.net/chaiwenjun000/article/details/45272709