Full Binary Tree

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

此题要求在一个二叉树中寻找两个数的最短路径,可知每个数都是同一个母数向下分裂;

所以只要找到两个数最近的母数就可的两数之间的最短路径;

只需每次对较大的数除以二即可;

AC代码:

#include <iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
struct A{
    char a[1100];
    char b[1100];
}a;
int main()
{
     int i,j,k,n,m,x,y,b,c,d,e,t;
     char a[110][110];
    while(scanf("%d",&t)!=EOF)
    {
        while(t--)
        {


            scanf("%d%d",&x,&y);
            for(m=0;x!=y;m++)
            {
                if(x>y)
                x/=2;
                 else if(y>x)
                y/=2;


            }


            printf("%d\n",m);
        }
    }




    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值