Full Binary Tree(二叉树找规律)

时间:2023-12-21 09:40:26

Description

In computer science, a binary tree is a tree data structure in which each node has at most two children. Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2 * v and its right child will be labelled 2 * v + 1. The root is labelled as 1.
You are given n queries of the form i, j. For each query, you have to print the length of the shortest path between node labelled i and node labelled j.

Input

First line contains n(1 ≤ n ≤ 10^5), the number of queries. Each query consists of two space separated integers i and j(1 ≤ i, j ≤ 10^9) in one line.

Output

For each query, print the required answer in one line.

Sample Input

5
1 2
2 3
4 3
1024 2048
3214567 9998877

Sample Output

1
2
3
1
44

Hint

Full Binary Tree(二叉树找规律)

题目意思:这是一个二叉树,如上图所示,给出二叉树上的而已两个点求出一点到另一点最短的距离或者说是步数。

解题思路:我们知道二叉树相当于一个自上而下的三角形,任意两个点在上方一定有一个点相交,称其为节点,我们只要找到那个节点就可以了,两点到节点的距离就是最短距离。

 #include<stdio.h>
#include<string.h>
int main()
{
int t;
long long a,b,m,n,count;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&a,&b);
count=;
while()
{
if(a>b)///两个数较大的那一个减半上移,不断逼近节点
{
a=a/;
count++;
}
if(b>a)
{
b=b/;
count++;
}
if(b==a)
break;
}
printf("%lld\n",count); }
return ;
}