POJ 2499 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: 
  • The root contains the pair (1, 1). 
  • If a node contains (a, b) then its left child contains (a + b, b) and its right child (a, a + b)

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*109) 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

#include<iostream> using namespace std; typedef struct { int  left ; int  right ; int   leftcount; int   rightcount; }Node; int main() { Node  node; int C; cin >> C; for (int i = 1; i <= C; i++) { cout << "Scenario #" << i << ":" << endl; cin >> node.left >> node.right; node.rightcount = 0; //注意每次输入新的数据时,记的次数要清零,不然会累加的 node.leftcount = 0; while ((node.left!= 1 ||node.right!= 1)) { if (node.left >= node.right) { int t=1; //也可以采用减法,但是运行时间会比较长,

//用node.left-1是避免最后变成0,根是(1,1) t = (node.left-1) / node.right; node.left = node.left-t*node.right; node.rightcount+=t; } else  { int f; f = (node.right-1) / node.left; node.right = node.right-f*node.left; node.leftcount+= f; } } cout << node.rightcount << " " << node.leftcount << endl<<endl; //一定要注意空格,千万不能 //多打,我多打了一个,就一直出现显示错误 } // system("pause"); return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值