码迷,mamicode.com
首页 > 其他好文 > 详细

Full Binary Tree

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

标签:图片   roo   step   没有   c++   print   tin   query   follow   

题目来源

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

标签:图片   roo   step   没有   c++   print   tin   query   follow   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!