Python筆試——Stern-Brocot tree
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 A/B and C/D is defined as (A+C)/(B+D).
Given a rational number in form of P/Q, find the position of P/Q in the Stern-Brocot Tree.
輸入描述:
Input consists of two integers, P and Q (1<=P,Q<=1000), which represent the rational number P/Q. We promise P and Q are relatively prime.
輸出描述:
Output consists of two integers, R and C.
R indicates the row index of P/Q in the Stern-Brocot Tree, C indicates the index of P/Q in the row.
We promise the position of P/Q is always in the first 12 rows of the Stern-Brocot tree, which means R<=12.
輸入例子1:
5 3
輸出例子1:
4 6
思路:
在這裡我嘗試用遞迴的方式來實現此功能。
具體而言,要定義一個尋找目標分數位置的函式search:
search(P,Q,X,Y,Row,Col,Lx,Ly,Rx,Ry)
這裡的P/Q為要尋找的目標分數,X/Y為 當前已經找到的分數,Row與Col分別為當前找到的分數X/Y所在的位置,Lx/Ly,Rx/Ry分別為要想找到X/Y所用的兩個數,即X =Lx+Rx,Y =Ly+Ry。
當向左搜尋時:
X(i+1)=X(i)+Lx(i),Y(i+1)=Y(i)+Ly(i),Row(i+1)=Row(i)+1,Col(i+1)=2*Col(i)-1,Lx(i+1)=Lx(i),Ly(i+1)=Ly(i),Rx(i+1)=X(i),Ry(i+1)=Y(i)
當向右搜尋時:
X(i+1)=X(i)+Rx(i),Y(i+1)=Y(i)+Ry(i),Row(i+1)=Row(i)+1,Col(i+1)=2*Col(i),Lx(i+1)=X(i),Ly(i+1)=Y(i),Rx(i+1)=Rx(i),Ry(i+1)=Ry(i)
由此我們可以寫出程式碼如下:
def search(P,Q,X,Y,Row,Col,Lx,Ly,Rx,Ry): #終止條件 if P==X and Q==Y: return Row,Col #向左搜尋 if P/Q < X/Y: r,c = search(P,Q,X+Lx,Y+Ly,Row+1,2*Col-1,Lx,Ly,X,Y) return r,c #向右搜尋 if P/Q > X/Y: r,c = search(P,Q,X+Rx,Y+Ry,Row+1,2*Col,X,Y,Rx,Ry) return r,c getNumFromString = lambda x:list(map(int,x.strip().split())) p,q = getNumFromString(input()) R,C = search(p,q,1,1,1,1,0,1,1,0) print(R,C)