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


有关二叉树的问题,简单来说就是找出从 i 到 j(或者说从 j 到 i ) 的路径,从 1 到 2 只需一步,从 2 到 3 需要 2 -> 1 -> 3

 两步.......对二叉树没多少了解,这个题完全可以逻辑推出来。

这题只需要一直把两个数之间大的一方往上推(除 2 或者先减去 1 再除 2(分奇偶) ),总会有相等的时候。



代码如下:

#include <iostream>

using namespace std;

int main()
{
    long long n , i , j , max , min ;
    cin >> n ;
    while(n--)
    {
        int s = 0;
        cin >> i >> j ;
        max = i > j ? i : j ;
        min = j<= i ? j : i ;
        while(max!=min)
        {
            if(max%2==0)
                max /= 2 ;
            else
                max=(max-1) / 2 ;
            s++;
            i = max ;
            j = min ;
            max = i > j ? i : j ;
            min = j <= i ? j : i ;
        }
        cout << s <<endl ;
    }
    return 0;
}

展开阅读全文

没有更多推荐了,返回首页