Full Binary Tree(二叉樹找規律)

Descriptionnode

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.
 

Inputide

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

 

Outputspa

For each query, print the required answer in one line.
 

Sample Input3d

5
1 2
2 3
4 3
1024 2048
3214567 9998877

Sample Outputcode

1
2
3
1
44

Hintorm

題目意思:這是一個二叉樹,如上圖所示,給出二叉樹上的而已兩個點求出一點到另外一點最短的距離或者說是步數。blog

解題思路:咱們知道二叉樹至關於一個自上而下的三角形,任意兩個點在上方必定有一個點相交,稱其爲節點,咱們只要找到那個節點就能夠了,兩點到節點的距離就是最短距離。ip

 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()  4 {  5     int t;  6     long long a,b,m,n,count;  7     scanf("%d",&t);  8     while(t--)  9  { 10         scanf("%lld%lld",&a,&b); 11         count=0; 12         while(1) 13  { 14             if(a>b)///兩個數較大的那一個減半上移,不斷逼近節點 15  { 16                 a=a/2; 17                 count++; 18  } 19             if(b>a) 20  { 21                 b=b/2; 22                 count++; 23  } 24             if(b==a) 25                 break; 26  } 27         printf("%lld\n",count); 28 
29  } 30     return 0; 31 }
相關文章
相關標籤/搜索