山东省第五届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,节点数值最大不超过10e9。

求任意两个节点a和b之间的最短路径。


解题思路:

①求出较小节点所在的层数;

②使较大节点向上跳到较小节点所在的层数,每跳一次路径加1;

③此时两节点在同一层,同时向上跳直到a=b,每个节点每跳一次路径加1,则两节点一起跳路径加2;

④此时得到的路径长度就是a和b之间的最短路径。


AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int p[31];//2^30>N
const long long N=1000000010;
void f()
{
    int i;
    for(i=0; pow(2,i)<=N; ++i)
        p[i]=pow(2,i);//p[]保存2^i
}

int main()
{
    int t;
    f();
    scanf("%d",&t);
    while(t--)
    {
        int a,b;
         scanf("%d%d",&a,&b);
        if(a>b) swap(a,b);//令a始终小于等于b
        int ans=0;
        int pos;//较小的数a的层数为pos
        for(int i=0; i<31; i++)
            if(a>=p[i]&&a<p[i+1])
            {
                pos=i;
                break;
            }
        while(1)//改变b的层数使a和b在同一层上
        {
            if(b>=p[pos]&&b<p[pos+1])
                break;
            b/=2;
            ans++;//每跳一层路径加一
        }

        while(a!=b)//两个节点一起跳
        {
            a/=2;
            b/=2;
            ans+=2;//每个节点跳一次路径加1,两个节点同时跳就是加2
        }
        printf("%d\n",ans);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值