SDUT 2882 Full Binary Tree【思维】
2017-04-30 16:11
393 查看
Full Binary Tree
Time Limit: 2000MS Memory Limit: 65536KBSubmit Statistic Discuss
Problem Description
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 leftchild 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.
Input
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.
Output
For each query, print the required answer in one line.
Example Input
5 1 2 2 3 4 3 1024 2048 3214567 9998877
Example Output
1 2 3 1 44
Hint
Author
2014年山东省第五届ACM大学生程序设计竞赛题目大意:
二叉树遍历作为编号,问两个点之间的最短路。
思路:
ans=dist(1,i)+dist(1,j)-2*dist(1,Lca[i,j])
找父亲节点的过程不断/2即可。
Ac代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL ;
const LL MOD = 1000000000+7;
#define abs(x) (((x)>0)?(x):-(x))
/***************************************/
int path[500];
int path2[500];
int main(){
int t;
scanf("%d",&t);
while(t--)
{
int i,j;
scanf("%d%d",&i,&j);
int dist1=0;
int dist2=0;
while(i>1)
{
path[dist1]=i;
i/=2;
dist1++;
}
while(j>1)
{
path2[dist2]=j;
j/=2;
dist2++;
}
int flag=0;
int pos=-1;
for(int i=0;i<dist1;i++)
{
for(int j=0;j<dist2;j++)
{
if(path[i]==path2[j])
{
pos=path[i];
flag=1;
break;
}
}
if(flag==1)break;
}
int dist3=0;
while(pos>1)
{
pos/=2;
dist3++;
}
printf("%d\n",dist1+dist2-2*dist3);
}
}
相关文章推荐
- [ACM] sdut 2882 Full Binary Tree (满二叉树的公共祖先)
- 山东省第五届省赛 F - Full Binary Tree (利用满二叉树性质的一个思维题)
- 山东省第五届省赛回顾 Full Binary Tree
- 山东省第五届省赛回顾 Full Binary Tree
- 2014年山东省第五届ACM--Full Binary Tree (满二叉树)
- Full Binary Tree
- Full Binary Tree Picture hiho一下第 177 周
- full binary tree != 满二叉树
- hdu 6161--Big binary tree(思维--压缩空间)
- [HihoCoder]#1342 : Full Binary Tree Picture
- 2014山东省第五届ACM省赛 Full Binary Tree
- 满二叉树(Full Binary Tree)&&完全二叉树(Complete Binary Tree)
- 第五届ACM大学生程序设计竞赛:Full Binary Tree
- [geeks]Construct Full Binary Tree from given preorder and postorder traversals
- Difference between Full Binary Tree and Complete Binary Tree
- 山东省第五届ACM大学生程序设计竞赛-Full Binary Tree(二叉树&&求任意两节点路径)
- Full Binary Tree(二叉树)
- Construct Full Binary Tree from given preorder and postorder traversals
- Full Binary Tree(有关二叉树)
- Data Structure Binary Tree: Construct Full Binary Tree from given preorder and postorder traversals