The Stern-Brocot tree is an infinite complete binary tree in which the vertices correspond one-for-one to the positive rational numbers, whose values are ordered from the left to the right as in a search tree. Figure 1 shows a part of the Stern-Brocot tree, which has the first 4 rows. Each node in the tree is marked in a red cycle. The value in the node is the mediant of the left and right fractions. The mediant of two fractions AB and CD is defined as (A+C)(B+D). To construct the Stern-Brocot tree, we first define the left fraction of the root node is 01, and the right fraction of the root node is 10. So the value in the root node is the mediant of 01 and 10, which is (0+1)(1+0)=11. Then the value of root node becomes the right fraction of the left child, and the left fraction of the right child. For example, the 1st node in row2 has 01 as its left fraction and 11(which is the value of its parent node) as its right fraction. So the value of the 1st node in row2 is (0+1)(1+1)=12. For the same reason, the value of the 2nd node in row2 is (1+1)(1+0)=21. This construction progress goes on infinitly. As a result, every positive rational number can be found on the Stern-Brocot tree, and can be found only once. Given a rational number in form of PQ, find the position of PQ in the Stern-Brocot Tree.
输入描述:
Input consists of two integers, P and Q (1=P,Q=1000), which represent the rational number PQ. We promise P and Q are relatively prime.
输出描述:
Output consists of two integers, R and C.R indicates the row index of PQ in the Stern-Brocot Tree, C indicates the index of PQ in the row.Both R and C are base 1.We promise the position of PQ is always in the first 12 rows of the Stern-Brocot tree, which means R=12.
加载中...