Description
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
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
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; }
本文探讨了在一种特殊的无限二叉树中寻找特定节点的最短路径,并提供了一种算法来确定从根节点到达该节点的过程中左子节点和右子节点的选择次数。
1390

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



