题目描述
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.
输入
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.
输出
For each query, print the required answer in one line.
示例输入
5 1 2 2 3 4 3 1024 2048 3214567 9998877
示例输出
1 2 3 1 44
根据满二叉树的性质,节点除以二一定是它的父节点。所以可以先以其中一个点遍历至树根,同时记录需要的步数,另一个再向上遍历,遇到父节点就对比,如果相同则两个点的步数相加
#include <stdio.h>
#include<iostream>
#define MAXN 10000000
using namespace std;
struct step
{
int node,cnt;
};
step s[MAXN];
int main()
{
int n,right,left,i,j,ct;
scanf("%d",&n);
while(n--)
{
i=0;
j=0;
scanf("%d%d",&right,&left);
s[0].node=right;
s[0].cnt=0;
i++;
while(right!=1)
{
right/=2;
s[i].node=right;
s[i].cnt=i;
i++;
}
ct=0;
while(1)
{
if(left>s[j].node)
{
left/=2;
ct++;
}
if(left==s[j].node)
{
ct+=s[j].cnt;
break;
}
if(left<s[j].node)
j++;
}
cout<<ct<<endl;
}
return 0;
}