#P1797. 【模板】Stern-Brocot 树

【模板】Stern-Brocot 树

Description

Conventions:

  • In this problem, all fractions in the input/output must be in lowest terms.
  • In this problem, every input fraction pq\dfrac{p}{q} satisfies 1p,q1091 \le p,q \le 10^9.

Task 1: ENCODE_PATH

  • Input format: ENCODE_PATH pp qq;
  • Output format: kk n1n_1 c1c_1 n2n_2 c2c_2 \cdots nkn_k ckc_k.

Given a fraction pq\dfrac{p}{q}, output the path from the root of the Stern-Brocot tree to the node pq\dfrac{p}{q} in the following format:

kk n1n_1 c1c_1 n2n_2 c2c_2 \cdots nkn_k ckc_k

Here ci{L,R}c_i \in \{\texttt{L}, \texttt{R}\} means go to the left or right child, and nin_i is how many times to repeat cic_i. You must ensure 1i<k\forall 1 \le i < k, cici+1c_i \ne c_{i+1}.

Task 2: DECODE_PATH

  • Input format: DECODE_PATH kk n1n_1 c1c_1 n2n_2 c2c_2 \cdots nkn_k ckc_k;
  • Output format: pp qq.

Given a path from the root in the same format as in Task 1, output the fraction on that node. It is guaranteed that the answer satisfies 1p,q1091 \le p,q \le 10^9.

Task 3: LCA

Given ab\dfrac{a}{b} and cd\dfrac{c}{d}, output the fraction pq\dfrac{p}{q} on the LCA of ab\dfrac{a}{b} and cd\dfrac{c}{d}.

  • Input format: LCA aa bb cc dd;
  • Output format: pp qq.

Task 4: ANCESTOR

Given ab\dfrac{a}{b} and kk, output the value pq\dfrac{p}{q} of the node whose depth is kk on the chain from ab\dfrac{a}{b} up to the root. If it does not exist, output 1-1.

  • Input format: ANCESTOR kk aa bb;
  • Output format: pp qq.
  • Constraints: 1k1091 \le k \le 10^9.

Task 5: RANGE

Given pq\dfrac{p}{q}, let SS be the set of all fractions in the subtree of pq\dfrac{p}{q} in the Stern-Brocot tree. Output infS=ab\inf S = \dfrac{a}{b} and supS=cd\sup S = \dfrac{c}{d}.

In particular, for 00, output 00 11; for ++\infty, output 11 00.

  • Input format: RANGE pp qq;
  • Output format: aa bb cc dd.

Input Format

The first line contains a positive integer TT, the number of test cases.

Each of the next TT lines describes one task, in the formats given in the Description.

Output Format

Output TT lines, each containing the answer to the corresponding task, in the formats given in the Description.

10
DECODE_PATH 0
DECODE_PATH 3 R 2 L 1 R 2
ENCODE_PATH 1 1
ENCODE_PATH 5 11
LCA 2 3 3 5
LCA 5439 19294 8291 29410
ANCESTOR 10 1 1
ANCESTOR 300 1000000000 1
RANGE 1 1
RANGE 11 8
1 1
11 4
0
2 L 2 R 4
2 3
148 525
-1
301 1
0 1 1 0
4 3 7 5

Hint

  • 1T1051 \le T \le 10^5.
  • All input fractions are in lowest terms.
  • Every input fraction pq\dfrac{p}{q} satisfies 1p,q1091 \le p,q \le 10^9.

Translated by ChatGPT 5