题目描述

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

分析:对于一颗满的完全二叉树来说,从叶子节点i 到根节点的最短路径长度为logi 向下取整。由于i ≤ 10^9,因此最短路径长度不会超过31,所以树中任意两个节点间的最短路径长度不会超过62。这说明用int 可以存下最多路径长度。至于求这个长度,简单递归(类比于求最大公共祖先)就可以办到:

#include<stdio.h> // 40MS
int count;
void f(int i, int j);
int main(void)
{
int n, i, j; scanf("%d", &n);
while(n--)
{
scanf("%d%d", &i, &j);
count = ;
f(i, j);
printf("%d\n", count);
}
} void f(int i, int j)
{
if(i == j)
return;
count++;
if(i > j)
return f(i/, j);
else
return f(i, j/); }

最新文章

  1. 【亚瑟士 ASICS 系列】
  2. .NET导入导出Excel
  3. CF #305 (Div. 2) C. Mike and Frog(扩展欧几里得&amp;&amp;当然暴力is also no problem)
  4. NSNotificationCenter
  5. [原创]PostgreSQL Plus Advanced Server监控工具PEM(一)
  6. ASP.net中GridView中增加一行记录并默认显示为编辑状态
  7. Go语言程序的状态监控 via 达达
  8. U3D 2D游戏之黑暗纪元 2D游戏基础入门开发全(1)
  9. Mock和injectMocks的区别
  10. rsync从windows到linux的同步备份
  11. mysql同时update多行
  12. STM32 + RT Thread OS 学习笔记[四]
  13. redis数据库操作的C++简单封装
  14. 李航《统计学习方法》CH02
  15. VS 在创建C#类时添加文件描述
  16. Vue.js文档
  17. 第二十七篇-新建Activity
  18. 在Github和oschina上搭建自己的博客网站
  19. Codeforces Round #510 (Div. 2)(A)
  20. python小记

热门文章

  1. Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal前序与中序构造二叉树
  2. 通过游戏学python 3.6 第一季 第八章 实例项目 猜数字游戏--核心代码--猜测次数--随机函数和屏蔽错误代码--优化代码及注释--简单账号密码登陆--账号的注册查询和密码的找回修改--锁定账号--锁定次数
  3. JS字符串的相关方法
  4. HTTP协议详解(经典)
  5. 异步 I/O 和事件驱动
  6. [DEPRECATION] Encountered positional parameter near xxx Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.
  7. NACOS集群搭建遇到的问题
  8. go语言:类型转换
  9. Oracle时间一串数字转为日期格式
  10. Leetcode671.Second Minimum Node In a Binary Tree二叉树中的第二小结点