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: |
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. |
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 }