您的位置:首页 > 其它

SDUT 2882 Full Binary Tree【思维】

2017-04-30 16:11 393 查看


Full Binary Tree

Time Limit: 2000MS Memory Limit: 65536KB

Submit 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 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.
 


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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SDUT 2882