#P16470. [GKS 2013 #A] Rational Number Tree

    ID: 16455 Type: RemoteJudge 1000ms 1024MiB Tried: 0 Accepted: 0 Difficulty: 3 Uploaded By: Tags>树形数据结构2013Google Kick Start

[GKS 2013 #A] Rational Number Tree

题目描述

Consider an infinite complete binary tree where the root node is 1/11/1 and left and right childs of node p/qp/q are p/(p+q)p/(p+q) and (p+q)/q(p+q)/q, respectively. This tree looks like:

:::align{center} :::

It is known that every positive rational number appears exactly once in this tree. A level-order traversal of the tree results in the following array:

1/11/1, 1/21/2, 2/12/1, 1/31/3, 3/23/2, 2/32/3, 3/13/1, \dots

Please solve the following two questions:

  1. Find the nn-th element of the array, where nn starts from 11. For example, for the input 22, the correct output is 1/21/2.
  2. Given p/qp/q, find its position in the array. As an example, the input 1/21/2 results in the output 22.

输入格式

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case consists of one line. The line contains a problem id (11 or 22) and one or two additional integers:

  1. If the problem id is 11, then only one integer nn is given, and you are expected to find the nn-th element of the array.
  2. If the problem id is 22, then two integers pp and qq are given, and you are expected to find the position of p/qp/q in the array.

输出格式

For each test case:

  1. If the problem id is 11, then output one line containing "Case #x: p q", where xx is the case number (starting from 11), and p,qp, q are numerator and denominator of the asked array element, respectively.
  2. If the problem id is 22, then output one line containing "Case #x: n", where xx is the case number (starting from 11), and nn is the position of the given number.
4
1 2
2 1 2
1 5
2 3 2
Case #1: 1 2
Case #2: 2
Case #3: 3 2
Case #4: 5

提示

Limits

1T1001 \le T \le 100; pp and qq are relatively prime.

Test set 1 - Visible

1n,p,q21611 \le n, p, q \le 2^{16}-1; p/qp/q is an element in a tree with level number 16\le 16.

Test set 2 - Hidden

1n,p,q26411 \le n, p, q \le 2^{64}-1; p/qp/q is an element in a tree with level number 64\le 64.