2014年山东省第五届ACM--Full Binary Tree (满二叉树)

Full Binary Tree
Time Limit: 2000MS Memory limit: 65536K
题目描述
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


来源

2014年山东省第五届ACM大学生程序设计竞赛

题意:

已知满二叉树,根节点编号为1,节点v的左右孩子编号依次为2*v、2*v+1,求从某一节点到另一节点之间的路径长度,例如从4到3路径为4-->2-->1-->3,需要3步,,,


思路:

从较大的节点开始不断的往上找,节点编号除以2便是他的父节点,每找一次每走一步路径加一,直到两个节点编号相同,,,


以下AC代码:

#include <stdio.h>  
int main()  
{  
    int i,j;  
    int n,m;  
    int T;  
    scanf("%d",&T);  
    while(T--)  
    {  
        int count=0;  
        scanf("%d %d",&n,&m);  
        while(n!=m)  
        {  
            if(n>m)  
                n/=2;  
            else  
                m/=2;  
            count++;  
        }  
        printf("%d\n",count);  
    }  
      
    return 0;  
}  


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值