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
题意:本题为二叉树查找左右孩子到共同节点的最短路径,由二叉树模型可知,每次i或j每次除2,都到达上一层节点的位置,左右孩子中大的不断除2,直到i与j相等为止,此时达到共同节点,每次除2用计数器记起来,最后所得便为最短路径。
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int t,a,b,c,s=0;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
s=0;
if(a<b)
{
c=a;
a=b;
b=c;
}
while(a!=b)
{
while(a>b)
{
a/=2;
s++;
}
c=a;
a=b;
b=c;
}
printf("%d\n",s);
}
return 0;
}
<stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int t,a,b,c,s=0;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
s=0;
if(a<b)
{
c=a;
a=b;
b=c;
}
while(a!=b)
{
while(a>b)
{
a/=2;
s++;
}
c=a;
a=b;
b=c;
}
printf("%d\n",s);
}
return 0;
}
萌新代码,如有不足,请多包含^_^