首页 > 其他 > 详细

Full Binary Tree

时间:2021-04-12 15:20:56      阅读:13      评论:0      收藏:0      [点我收藏+]

题目来源

Full Binary Tree

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,it‘s left children will be labelled 2v and it‘s right child will be labelled 2v+1.The
root is labelled 1.

技术分享图片

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.
技术分享图片

AC代码

#include<bits/stdc++.h>
using namespace std;

long long Path(long long x,long long y);
int main(){
	int n;
	long long a,b;
	cin >> n;
	for(int t=0;t<n;t++){
		scanf("%lld%lld",&a,&b);
		//cin >> i >> j;
		long long ans = Path(a,b);
		cout << ans << endl;
	} 
	return 0;
} 

long long Path(long long x,long long y){
	
	
	int step = 0;
	while(x!=y){
		if( x > y){
			x = x/2;
			step++;
		}else if(x < y){
			y = y/2;
			step++;
		}

	}
	return step;
}

错误集锦

刚开始,没有把握好题目求解的本质。将Path函数写成了如下方式:

long long Path(long long x,long long y){
	
	
	int step = 0;
	while(x!=y){
		if(x % y == 0){
			x /= 2;
			step++;
			continue;
		}
		
		if(y % x == 0){
			y /= 2;
			step++;
			continue;
		}
		//cout << ":" << x << " " << y << " step = " << step << endl;
		x = x/2;
		y = y/2;
		//cout << " x = " << x << " y = " << y << " step = " << step <<endl;
		step += 2;

	}
	return step;
}

这样写是错的,虽然题目提供的案例是过的。我应该测试下(7,15)或者(2,5)或者(x,2x+1)这样的例子就好了。

Full Binary Tree

原文:https://www.cnblogs.com/ManOK/p/14647627.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!