A Rational Sequence 二叉树DFS

A Rational Sequence
Time Limit: 4000ms, Special Time Limit:10000ms, Memory Limit:65536KB
Total submit users: 9, Accepted users: 9
Problem 13567 : No special judgement
Problem description

A sequence of positive rational numbers is defined as follows:
An infinite full binary tree labeled by positive rational numbers is defined by:
 The label of the root is 1/1.
 The left child of label p/q is p/(p+q).
 The right child of label p/q is (p+q)/q.
The top of the tree is shown in the following figure
  The sequence is defined by doing a level order (breadth first) traversal of the tree (indicated by the light dashed line). So that:
F(1) = 1/1, F(2) = 1/2, F(3) = 2/1, F(4) = 1/3, F(5) = 3/2, F(6) = 2/3, …
Write a program which finds the value of n for which F(n) is p/q for inputs p and q.

Input

The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set should be processed identically and independently.
Each data set consists of a single line of input. It contains the data set number, K, a single space, the numerator, p, a forward slash (/) and the denominator, q, of the desired fraction.

Output

For each data set there is a single line of output. It contains the data set number, K, followed by a single space which is then followed by the value of n for which F(n) is p/q. Inputs will be chosen so n will fit in a 32-bit integer.

Sample Input
4
1 1/1
2 1/3
3 5/2
4 2178309/1346269
Sample Output
1 1
2 4
3 11
4 1431655765
Problem Source

GNY 2015

题意:给一个二叉树,顶点为p/q,左儿子为p/(p+q),右儿子为(p+q)/q。已知该节点的权值,求该节点的位置,顺序如图所示。

 该二叉树的性质:左边的p<q,位置为2n,右边的p>q,位置为2n+1。从要找的位置从上往上搜,然后从上往下重新寻找该位置。用递归进行记录。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<iostream>
 5 using namespace std;
 6 int dfs(int p,int q)
 7 {
 8     if(p==q&&p==1) return 1;
 9     if(p<q) return dfs(p,q-p)*2;
10     else return dfs(p-q,q)*2+1;
11 }
12 main()
13 {
14     int t,n,p,q;
15     scanf("%d",&t);
16     while(t--)
17     {
18         scanf("%d %d/%d",&n,&p,&q);
19         printf("%d %d\n",n,dfs(p,q));
20     }
21 }

 

posted @ 2016-07-25 19:26  Crazy、baby  阅读(271)  评论(0编辑  收藏  举报