Full Binary Tree
Title Link: http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2882
Time limit:2000ms Memory limit:65536k have questions? Dot here ^_^ The topic description in Computer science, a binary tree is a tree data structure in which each node had at the most of the children. Consider an infinite full binary tree (each node has a children except the leaf nodes) defined as follows. The for a node labelled V it left child would be labelled 2?*?v and its right child would 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 had to print the length of the shortest path between node labelled I and node labelled J. Input first Lin E contains n (1?≤?n?≤?10^5), the number of queries. Each query consists of one space separated integers i and J (1?≤?i,?j?≤?10^9) in one line. Output for each query, print the required answer on one line. Sample input
51 22 34 31024 20483214567 9998877
Sample output
123144
Hint Source 2014 The fifth annual ACM College Student Program Design competition in Shandong Province
Problem Solving Ideas:
Test instructions is given a full two fork tree, the number of root node is 1, the left child node is the parent node twice times, the right child node is the parent node twice times plus 1;
1
2 3?
4 5 6 7 You can see the number of each layer x satisfies 2^p <=x<2^ (p+1) (p for number of layers)
8 9 10 11 12 13 14 15
What is asked is two numbers in a given binary tree, to find the shortest distance, that is, to find the nearest public parent node
#include <iostream> #include <algorithm>using namespace std;const int Maxn=99999;int f[maxn];int len;void Init ()//Initialize, draw full two fork tree {f[0]=1;for (int i=1;; i++) {f[i]=f[i-1]*2;if (f[i]>1e9) {len=i-1;break;}}} int main () {init ();//cout<< "Len" <<len<<endl;int t;cin>>t;while (t--) {int A,b;int step=0;cin >>a>>b;if (a>b) swap (A, b);//used to represent a larger number int pos; The POS represents the smaller number in the layer for (int i=0;i<len;i++) {if (a>=f[i]&&a<f[i+1])//To find the number of layers in the smaller number {pos=i;break;}} while (1) {if (b>=f[pos]&&b<f[pos+1])//The larger number jumps up until the same layer break;else{b/=2;step++ with the smaller number;}} while (a!=b) {b/=2; Then two numbers go up and jump a/=2;step+=2;} Cout<<step<<endl;} return 0;}
The fifth session of Shandong Province race review full Binary Tree