Full Binary Tree 2014 SD第五届ACM大学生程序设计竞赛 F
来源:互联网 发布:淘宝官换机哪家好 编辑:程序博客网 时间:2024/05/07 11:21
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
求完全二叉树中任意两个节点的最短距离
分别求出两个节点到根节点的路径,依次比较路径,找到第一个不同的节点就是最低公共祖先,然后路径值相加即可,注意对边界情况处理#include <iostream>#include <cstring>using namespace std;int T,i,j,m,n,k,dis;int pathi[33],pathj[33];/分别保存i,j节点到根节点的路径int main(){ cin >> T; while(T--) { m = n = 0; memset(pathi,0,sizeof(pathi)); memset(pathj,0,sizeof(pathj)); cin >> i >> j; while(i)//求i路径 { pathi[m++] = i; i = i / 2; } while(j)//求j路径 { pathj[n++] = j; j = j / 2; } m--;n--; while(pathi[m] == pathj[n] && m && n) {m--;n--;}//找到最低公共祖先//循环结束条件有多种 if(!n && !m) dis =(pathi[0] == pathj[0]) ? 0 : 2;//当两个下标都为0时,若pathi[0] != payhj[0],则ij为兄弟关系,相同时为父子关系 else if(pathi[m] == pathj[n]) dis = (!m) ? n : m;//如果pathi[m]==pathj[n],此时一定会有一个下标为0,则取非0的那个下标 else {m++;n++;dis = m + n;}//此时不会有任何下标为0,即pathi[m++]==pathj[n++]且为最低公共祖先,此时n+1、m+1分别代表i、j到公共祖先//的距离 cout << dis << endl; } return 0;}
0 0
- Full Binary Tree 2014 SD第五届ACM大学生程序设计竞赛 F
- 山东省第五届ACM大学生程序设计竞赛 Full Binary Tree
- 第五届ACM大学生程序设计竞赛:Full Binary Tree
- Full Binary Tree(山东省第五届ACM大学生程序设计竞赛 )
- 山东省第五届ACM大学生程序设计竞赛-Full Binary Tree(二叉树&&求任意两节点路径)
- 第五届ACM大学生程序设计竞赛:angry_birds_again_and_again
- 第五届山东省ACM Full Binary Tree
- 2014山东省第五届ACM省赛 Full Binary Tree
- 2014山东省第五届ACM省赛 Full Binary Tree
- “浪潮杯”山东省第八届ACM大学生程序设计竞赛F
- 河南省第五届acm大学生程序设计竞赛总结
- “浪潮杯”第五届ACM大学生程序设计竞赛
- 山东省第五届ACM大学生程序设计竞赛-angry_birds_again_and_again(积分)
- 山东省第五届ACM大学生程序设计竞赛 angry_birds_again_and_again 求积分
- 山东省第五届ACM大学生程序设计竞赛 Weighted Median
- 第五届ACM大学生程序设计竞赛:Hearthstone II
- 山东省第五届ACM大学生程序设计竞赛 Colorful Cupcakes
- Circle(山东省第五届ACM大学生程序设计竞赛 )
- 1800 Flying to the Mars
- 【索引】General Problem Solving Techniques:Examples:Beginner
- hdu 1387 Team Queue(队列的嵌套)
- TextView的setText方法出错
- E:Encountered a section with no Package: header, E:Problem with MergeList /var/lib/apt/lists/cn.arch
- Full Binary Tree 2014 SD第五届ACM大学生程序设计竞赛 F
- 敏捷开发之需求澄清
- A*算法
- sea.js介绍
- 04 Session接口及getloadpersist方法
- 北沫旗舰店小智男装英雄联盟ezm怎么样,质量好吗淘宝北沫旗舰店小智男装英雄联盟ezm怎么样,质量好吗
- 【索引】General Problem Solving Techniques:Examples
- 8.3简要说明RFID系统的时隙ALOHA算法的工作过程。
- 【索引】General Problem Solving Techniques:Examples:Intermediate