[ACM] sdut 2882 Full Binary Tree (满二叉树的公共祖先)
来源:互联网 发布:斗鱼皇帝 知乎 编辑:程序博客网 时间:2024/04/28 05:38
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.
示例输入
51 22 34 31024 20483214567 9998877
示例输出
123144
提示
来源
2014年山东省第五届ACM大学生程序设计竞赛
题意为一棵满二叉树,父节点编号为i,左孩子节点为i*2,右孩子节点编号为i*2+1,根节点编号为1,给定两个节点编号a,b,问a,b之间的最短路径是多少。
也就是求a,b的最近公共祖先。满二叉树每一层节点的编号x满足 2^p<=x<2^(p+1),所以先求出编号较小的数在哪一层,然后大的数跳到那一层,然后两个节点一起跳就可以了。
代码:
#include <iostream>using namespace std;int f[10000];//f[i]保存的是2的i次方int len;void pre(){ f[0]=1; for(int i=1;;i++) { f[i]=f[i-1]*2; if(f[i]>1e9) { len=i-1; break; } }}int a,b;int t;int main(){ pre(); cin>>t; while(t--) { cin>>a>>b; if(a>b) swap(a,b); int step=0; int pos;//找到较小的数a在哪一层上,用pos保存 for(int i=0;i<len;i++) { if(a>=f[i]&&a<f[i+1]) { pos=i; break; } } while(1)//较大的数跳到与较小的数同一层上去 { 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
- [ACM] sdut 2882 Full Binary Tree (满二叉树的公共祖先)
- LeetCode 236. Lowest Common Ancestor of a Binary Tree(二叉树的最低公共祖先)
- 2014年山东省第五届ACM--Full Binary Tree (满二叉树)
- 二叉搜索树(BST)的最近公共祖先(LCA)问题(Lowest Common Ancestor of a Binary Tree)
- 二叉树中两个结点的最近公共祖先(Lowest Common Ancestor of a Binary Tree)
- LeetCode 235 Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最小公共祖先)
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree(二叉搜索树的最低公共祖先)
- 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最低公共祖先(难)
- 235. Lowest Common Ancestor of a Binary Search Tree (求二叉树中两个节点的最近公共祖先)
- Lowest Common Ancestor of a Binary Tree 二叉树的公共祖先
- Lowest Common Ancestor of a Binary Search Tree(二叉树最小公共祖先)
- full binary tree != 满二叉树
- SDUT 2882 Full Binary Tree【思维】
- 山东省第五届ACM省赛题——Full Binary Tree(二叉树应用)
- ACM:A: 二叉树结点公共祖先
- 满二叉树的最近公共祖先
- [Java]寻找最低公共祖先(排序二叉树)Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree 递归寻找二叉查找树公共祖先
- Prime Ring Problem(杭电1016)(DFS)
- adb 指令大全
- 《数据结构》C++代码 线性表
- 侦测WebApp的启动与结束
- Android组件Service学习
- [ACM] sdut 2882 Full Binary Tree (满二叉树的公共祖先)
- 2.6.18内核移植
- EBS R12安装升级(FRESH)(二)
- 又见Alice and Bob
- [C++]LeetCode: 33 Combination Sum
- uboot之makefile源码
- Session生命周期以及内部实现原理
- Reorder List
- 云计算大赛&hadoop2.4.1安装