UVa 10077 - The Stern-Brocot Number System

10077 - The Stern-Brocot Number System

 * http://uva.onlinejudge.org/external/100/10077.html

Summary
This problem involves divide & conquer but can be solved using some properties of Stern-Brocot tree.

Explanation
Stern-Brocot tree has some beautiful properties. We don't need to design a divide & conquer fashioned code, rather there are some interesting tricks. If we start with irreducible fractions representing zero and infinity,

$$\frac{0}{1},\frac{1}{0}$$

and then between adjacent fractions $$\frac{m}{n}$$ and $$\frac{\acute{m}}{\acute{n}}$$ we insert fraction $$\frac{m+\acute{m}}{n+\acute{n}}$$, then we obtain,

$$\frac{0}{1},\frac{1}{1},\frac{1}{0}$$

Repeating this process, we get,

$$\frac{0}{1},\frac{1}{3},\frac{1}{2},\frac{2}{3},\frac{1}{1},\frac{3}{2},\frac{2}{1},\frac{3}{1},\frac{1}{0}$$

and so forth. It can be proven that every irreducible fraction appears at some iteration and no fraction ever appears twice. The process can be represented graphically by means of so-called Stern-Brocot tree, named after its discoverers, Moritz Stern and Achille Brocot.

If we specify position of a fraction in the tree as a path consisting of L(eft) an R(ight) moves along the tree starting from the top (fraction $$\frac{1}{1}$$), and also define matrices,

$$L = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, R = \begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix}$$

then product of the matrices corresponding to the path is matrix $$L = \begin{bmatrix} n & \acute{n} \\ m & \acute{m} \end{bmatrix}$$ whose entries are numerators and denominators of parent fractions. For example, the path leading to fraction $$\frac{3}{5}$$ is $$LRL$$. The corresponding matrix product is,

$$LRL = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}\begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix} = \begin{bmatrix} 2 & 3 \\ 1 & 2 \end{bmatrix}$$

and the parents of $$\frac{3}{5}$$ are $$\frac{1}{2}$$ and $$\frac{2}{3}$$.

Continued fractions and Stern-Brocot tree are closely related. A continued fraction $$(a_0;a_1,a_2\dots)$$ corresponds to fraction whose path from the top is $$R^{a_0}R^{a_1}R^{a_2}\dots$$ with the last element removed. For example, $$\frac{5}{3} = 1+\frac{1}{1+\frac{1}{2}} = (1;1,2) = R^1L^1R^{2-1} = RLR$$ $$\frac{4}{11} = 0+\frac{1}{2+\frac{1}{1+\frac{1}{3}}} = (0;2,1,3) = R^0L^2R^1L^{3-1} = LLRLL$$

Pretty much cool, huh?

Gotchas

 * Take care of the scenario when m is less than n i.e. $$\frac{4}{11}$$.

Sample Input
5 7 878 323 1 1

Sample Output
LRRL RRLRRLRLLLLRLRRR

Implementation
C++: http://pastebin.com/bdAHFTbW