ACM第五届山东省赛 F-Full Binary Tree
Time Limit: 2000 ms Memory Limit: 65536 KiB
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.
Sample Input
5
1 2
2 3
4 3
1024 2048
3214567 9998877
Sample Output
1
2
3
1
44
题目链接:http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Index/problemdetail/pid/2882.html
本题的题意:给定满二叉树上的两个点,求它们之间的路径长度。
很容易想到的解法是将结点编号大的除以二,以此循环,每次计路径数加一,直到两个结点的编号相等。
参考代码
#include <stdio.h>
int main(void)
{
int n;
int i, j;
int sum;
scanf("%d", &n);
while(n--){
sum = 0;
scanf("%d%d", &i, &j);
while(i != j){
if(i > j){
i /= 2;
sum++;
}
else{
j /= 2;
sum++;
}
}
printf("%d\n", sum);
}
return 0;
}