Full Binary Tree
2018-03-19 19:36
288 查看
DescriptionIn 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. InputFirst 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. OutputFor each query, print the required answer in one line. Sample Input
所以只要找到两个数最近的母数就可的两数之间的最短路径;
只需每次对较大的数除以二即可;
AC代码:
#include <iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
struct A{
char a[1100];
char b[1100];
}a;
int main()
{
int i,j,k,n,m,x,y,b,c,d,e,t;
char a[110][110];
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
scanf("%d%d",&x,&y);
for(m=0;x!=y;m++)
{
if(x>y)
x/=2;
else if(y>x)
y/=2;
}
printf("%d\n",m);
}
}
return 0;
}
5 1 2 2 3 4 3 1024 2048 3214567 9998877Sample Output
1 2 3 1 44此题要求在一个二叉树中寻找两个数的最短路径,可知每个数都是同一个母数向下分裂;
所以只要找到两个数最近的母数就可的两数之间的最短路径;
只需每次对较大的数除以二即可;
AC代码:
#include <iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
struct A{
char a[1100];
char b[1100];
}a;
int main()
{
int i,j,k,n,m,x,y,b,c,d,e,t;
char a[110][110];
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
scanf("%d%d",&x,&y);
for(m=0;x!=y;m++)
{
if(x>y)
x/=2;
else if(y>x)
y/=2;
}
printf("%d\n",m);
}
}
return 0;
}
相关文章推荐
- Google Code Jam 2014 Round 1 A:Problem B. Full Binary Tree
- 2014年山东省第五届ACM--Full Binary Tree (满二叉树)
- Full Binary Tree(二叉树)
- 山东省第五届省赛回顾 Full Binary Tree
- 山东省第五届省赛回顾 Full Binary Tree
- 第五届山东省ACM Full Binary Tree
- Full Binary Tree(有关二叉树)
- Problem B. Full Binary Tree
- 山东省第五届省赛 F - Full Binary Tree (利用满二叉树性质的一个思维题)
- Construct Full Binary Tree from given preorder and postorder traversals
- hihocoder 1342 Full Binary Tree Picture【完全二叉树】
- 2014山东省第五届ACM省赛 Full Binary Tree
- SDUT 2882 Full Binary Tree【思维】
- 山东省第五届ACM大学生程序设计竞赛 Full Binary Tree
- 满二叉树(Full Binary Tree)&&完全二叉树(Complete Binary Tree)
- 山东省第五届ACM省赛题——Full Binary Tree(二叉树应用)
- Data Structure Binary Tree: Construct Full Binary Tree from given preorder and postorder traversals
- Full Binary Tree(山东省第五届ACM大学生程序设计竞赛 )
- 第五届ACM大学生程序设计竞赛:Full Binary Tree
- [ACM] sdut 2882 Full Binary Tree (满二叉树的公共祖先)