sdut 2882 完全二叉树两结点之间的最小距离
来源:互联网 发布:深孔爆破的爆破网络 编辑:程序博客网 时间:2024/05/16 06:44
Full Binary TreeTime 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.
示例输入
51 22 34 31024 20483214567 9998877
示例输出
123144
提示
解题思路:
题意为一棵满二叉树,父节点编号为i,左孩子节点为i*2,右孩子节点编号为i*2+1,根节点编号为1,给定两个节点编号a,b,问a,b之间的最短路径是多少。
也就是求a,b的最近公共祖先。满二叉树每一层节点的编号x满足 2^p<=x<2^(p+1),所以先求出编号较小的数在哪一层,然后大的数跳到那一层,然后两个节点一起跳就可以了
#include <iostream>#include<cmath>#include<cstdio>#include<algorithm>using namespace std;int len;int f[10000];///保存的是2的次幂void pre(){ f[0]=1; for(int i=1;;i++) { f[i]=2*f[i-1]; if(f[i]>1e9) { len=i-1; break; } }}int a,b,t;int main(){ pre(); cin>>t; while(t--) { cin>>a>>b; if(a>b) swap(a,b); int step=0; int pos; for(int i=0;i<len;i++) { if(a>=f[i]&&a<=f[i+1]) { pos=i; break; } } while(1)///b层跳到a层 { if(b>=f[pos]&&b<=f[pos+1]) break; b/=2; step++; } while(a!=b)///一起跳到同一个结点 { a/=2; b/=2; step+=2; } cout<<step<<endl; } return 0;}
0 0
- sdut 2882 完全二叉树两结点之间的最小距离
- 求二叉树中任意两结点的距离
- 求二叉树中任意两结点的距离
- 求二叉树结点的最大距离
- 二叉树结点的最大距离
- 二叉树中两个结点的距离
- 二叉树中两个结点的距离
- 二叉树中结点的最大距离
- 树中的两个结点之间的距离
- 第十一题:求二叉树任意两结点的最大距离
- 完全二叉树的结点数计算
- 完全二叉树的结点总数问题
- 二叉树结点最远距离
- 二叉树两结点的最低共同父结点
- 二叉树两结点的最低共同父结点
- 二叉树两结点的最低共同父结点
- 二叉树两结点的最低公共祖先结点(一)
- 二叉树两结点的最低共同父结点[数据结构]
- Poj 1458 Common Subsequence 最长非连续序列
- 第八周项目2-用对象数组操作长方柱类
- oledb 访问ACCESS
- Mouse without Borders 简单使用教程
- 线程模型演进
- sdut 2882 完全二叉树两结点之间的最小距离
- 关于GC的类型
- 程序员常用的十款软件
- Cocos2d-x 容器(二) Vector
- 程序员互动联盟第三届第一题
- 微软拥抱Linux,着实太晚了
- OmniGraffle Tips
- 正确配置Linux系统ulimit值的方法
- nginx配置location [=|~|~*|^~] /uri/ { … }用法