第五届ACM大学生程序设计竞赛:Full Binary Tree
2016-04-20 16:02
316 查看
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 anode 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大学生程序设计竞赛题目意思:
一个满二叉树,给你两个节点,求出这两个节点间的长度.
简单来说要先找到两个节点的最近的公共祖先.这样经过的路程才是可求的最短的路径.现在已知两个节点,只需不停的最大数除以二,直到a==b,这个时候表示已经达到最近的公共祖先.每次除的时候,ans+1,记录路径的长度.最后当a==b时,所求的即为俩个节点间的距离.
#include <iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int a,b; cin>>a>>b; if(a<b) swap(a,b); int ans=0; while(a!=b) { while(a>b) { a>>=1; ans++; } swap(a,b); } cout<<ans<<endl; } return 0; }
相关文章推荐
- github使用笔记-- GitHub Desktop 下载、安装、使用
- Zeppelin 安装部署实验
- 继承时的构造函数的的原则
- AJAX跨域请求PHP接口
- java内存布局图
- iOS 将原点移动到navigationBar下面(或UIScrollView和 cell加载子视图偏移64问题)
- js监听输入框值的即时变化onpropertychange、oninput
- 详解Python命令行解析工具Argparse
- RMAN异机恢复
- Android 常用布局及基本UI控件
- ActiveMQ实战之 Topic发布订阅消息
- JNI - Exception Handling
- Android插件化基础
- Android之"AES"加密解密
- 漏洞原理分析
- 腾讯后台研发暑期实习offer经历
- [Asp.net Mvc]通过UrlHelper扩展实现js,css修改后重新加载
- 帧布局,表格布局
- iOS应用程序内打开指定qq聊天、给某人打电话
- java中redis实现篇