|
Binary Tree
Description
Background
Binary trees are a common data structure in computer science. In this problem we will look at an infinite binary tree where the nodes contain a pair of integers. The tree is constructed like this:
Problem Given the contents (a, b) of some node of the binary tree described above, suppose you are walking from the root of the tree to the given node along the shortest possible path. Can you find out how often you have to go to a left child and how often to a right child? Input
The first line contains the number of scenarios.
Every scenario consists of a single line containing two integers i and j (1 <= i, j <= 2*10 9) that represent a node (i, j). You can assume that this is a valid node in the binary tree described above. Output
The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. Then print a single line containing two numbers l and r separated by a single space, where l is how often you have to go left and r is how often you have to go right when traversing the tree from the root to the node given in the input. Print an empty line after every scenario.
Sample Input 3 42 1 3 4 17 73 Sample Output Scenario #1: 41 0 Scenario #2: 2 1 Scenario #3: 4 6 Source
TUD Programming Contest 2005 (Training Session), Darmstadt, Germany
|
继续吐槽"数据结构编程实验"---题目描述有二叉树是没错,但是这道题是贪心或者递推(逆推)好吧
算法还是很漂亮的:
从 i,j开始逆推,i比j大的话就向左走,反之向右走.用除法代替减法减少循环次数
#include <iostream>
using namespace std;
int n,i,a,b,right1,left1,up;
int main()
{
cin>>n;
for (i=1;i<=n;++i){
cin>>a>>b;
left1=right1=0;
while (a>1 || b>1)
if (a>b){
up=(a-1)/b;
left1+=up;
a-=up*b;
}
else{
up=(b-1)/a;
right1+=up;
b-=up*a;
}
cout<<"Scenario #"<<i<<":"<<endl<<left1<<" "<<right1<<endl<<endl;
}
return 0;
}
kdwycz的网站: http://kdwycz.com/
kdwyz的刷题空间:http://blog.csdn.net/kdwycz

本文深入探讨了二叉树数据结构的基本概念,并通过实例详细解释了一个涉及无限二叉树的问题,旨在帮助读者理解如何从根节点到指定节点的最短路径中计算左右节点的访问频率。

415

被折叠的 条评论
为什么被折叠?



