第五届省赛题解——F Full Binary Tree

F - 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

题型:
二叉树的基本知识
题意:
给出一个无限完整的二叉树(每个节点有两个子节点,除了叶节点), 对于标记为v的节点,其左边的孩子标记为2 * v,右边的孩子标记为2 * v + 1,根标记为1。给出两个节点的编号,求两个节点之间的最短路径长度。节点编号i,就(1<=i,j<=1e9)每条边的长度为1。
题解:
因为1<=i,j<=1e9,所以树的最大深度不会超过31,因此通可以暴力找到,两个节点的公共根节点。因为要找最短路径,所以要输出标号最大的根节点到两个根节点的距离之和就可以了。也可以使用递归的方法得到答案。
暴力代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int a0[50],b0[50];
int main()
{
    int t;
    long long a,b;
    cin>>t;
    while (t--)
    {
        cin>>a>>b;
        int na=1,nb=1;
        a0[0]=a,b0[0]=b;
        while (a)
        {
            a0[na++]=a/2;
            a/=2;
        }
        while (b)
        {
            b0[nb++]=b/2;
            b/=2;
        }
        int ans=0,flag=0;
        for (int i=0; i<na; i++)
        {
            for (int j=0; j<nb; j++)
            {
                if (a0[i]==b0[j])
                {
                    ans=i+j;
                    flag=1;
                    break;
                }
                if (flag)
                    break;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

递归代码:

#include <iostream>
#include <cmath>
#include <cstdio>
#include<cstring>
using namespace std;
int ans;
void Find(long long n,long long m)
{

    if(n==m)
        return ;
        ans++;
    if(n>m)
         Find(n/2,m);
        else
         Find(n,m/2);
}
int main()
{
    int T;
    long long n,m;
    cin>>T;
    while(T--)
    {
        ans=0;
        cin>>n>>m;
        Find(n,m);
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值