2014山东省第五届ACM省赛 Full Binary Tree

来源:互联网 发布:2015云计算市场规模 编辑:程序博客网 时间:2024/05/19 16:35

Full Binary Tree

Time Limit: 2000MS Memory limit: 65536K

题目描述

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.
 

输入

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.
 

输出

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

示例输入

51 22 34 31024 20483214567 9998877

示例输出

123144

提示

 

来源

2014年山东省第五届ACM大学生程序设计竞赛

题意:给二叉树的两个结点标号i和j(标号从1开始),求它们间路径的长度。

思路:当i!=j时直接将大的一个除以2,不断循环,每次答案+1。

初始时两点深度可能不等,将深度大的不断减小,当两者深度相等时,若i==j则可输出答案。否则继续循环下去,它们的深度差为0或1,总会在某个时候i==j。

#include <iostream>   using namespace std;   int main()   {       int T,ans;       cin>>T;       while(T--)       {           int a,b,t;           ans=0;           cin>>a>>b;           t=a;           if(a<b)           {               a=b;               b=t;           }           while(a!=b)           {               a/=2;               ans++;               t=a;               if(a<b)               {                   a=b;                   b=t;               }           }           cout<<ans<<endl;       }       return 0;   }   

0 0
原创粉丝点击