2014山东省第五届ACM省赛 Full Binary Tree(找规律)

E - Full Binary Tree
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu
 use MathJax to parse formulas

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

题意是给你一颗二叉树,假设这个数的一个结点为v,那么他的左儿子为2*v,右儿子为2*v+1;

现在让求从i->j的最短路


其实并不是个最短路~~~



观察一下这个树

如果i为2,j为3,那么我们往上走,就有2>>1  =1,3 >>1  = 1;

这时候i 和j在同一个位置,证明他们相遇

总路径 = 1+1 = 2;

再讲一个例子,假如i = 5,j = 1;

此时i >> 1 = 2,j由于已经等于1了所以不移动;

i再次移动 2>>1 = 1;

两者相遇;

不懂得话可以看一下二叉树的结构图,每一个结点无限往上走是肯定能碰在一起的,而且由于

同一层之间不能直接穿过,所以当且仅当向上走,直到相遇时的路长为最短路长;

代码如下

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 1100
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
#define For(i,n) for(i=0;i<n;i++)
#define Pi 3.1415926535898
typedef long long ll;
int gcd(int a,int b){return b?gcd(b,a%b):a;}
int main()
{
    int t,a,b;
    int cnt = 0;
    cin >> t;
    while(t--){
        cin >> a>>b;
        cnt = 0;
        while(a!=1 || b!=1){
            if(a>b){
                a>>=1;
                cnt++;
            }
            else if(b>a){
                b>>=1;
                cnt++;
            }
            else
                break;
        }

        cout << cnt << endl;
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值