POJ 2499 Binary Tree
题目链接: POJ 2499
| Describe: |
| Background Binary trees are a common data structure in computer science. In this problem we will look at an infinite binary tree where the nodes contain a pair of integers. The tree is constructed like this:
Problem Given the contents (a, b) of some node of the binary tree described above, suppose you are walking from the root of the tree to the given node along the shortest possible path. Can you find out how often you have to go to a left child and how often to a right child? |
| Input: |
| The first line contains the number of scenarios. Every scenario consists of a single line containing two integers i and j (1 <= i, j <= 2*109) that represent a node (i, j). You can assume that this is a valid node in the binary tree described above. |
| Output: |
| The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. Then print a single line containing two numbers l and r separated by a single space, where l is how often you have to go left and r is how often you have to go right when traversing the tree from the root to the node given in the input. Print an empty line after every scenario. |
| Sample Input: |
| 3 42 1 3 4 17 73 |
| Sample Output: |
| Scenario #1: 41 0 Scenario #2: 2 1 Scenario #3: 4 6 |
题目大意:
有一个无限二叉树,每一个节点为一对整数,根节点为(1,1),若某节点为(a,b),则它的左儿子的数为(a+b,b),右儿子的数为(a,a+b),若给你一对数,让你判断从根节点到该节点,向左子树移动了几次,向右子树移动了几次。
解题思路:
刚开始想的是,从根节点向下写几项找规律,但是没做出来,后来发现老师的做法,倒着找,一下就会了,直接开始写,结果T了,发现普通法写的话会超时,让后就优化了一下,每一次向上找多层。
AC代码:
1 #include <iostream> 2 #include <cstdio> 3 #define ll long long 4 using namespace std; 5 int main() 6 { 7 ll t,r,l; // 各种变量 8 ll cnt = 0; // 计数器 9 scanf("%lld",&t); 10 while(t--) 11 { 12 r = l = 0; // 答案初始化 13 ll i,j; 14 scanf("%lld%lld",&i,&j); 15 while(1) 16 { 17 if(i == j && i == 1 && j == 1) break; // 算到根节点就退出 18 if(i > j) // 左子树 19 { 20 if(i - j >= j) // 优化,一回计算多个,但是需要特判,不然会无限循环 21 { 22 l += (i-j)/j; 23 i -= (i-j)/j*j; 24 } else if(i-j < j) { 25 l++; 26 i = i - j; 27 } 28 } else if(i < j) { // 右子树 29 if(j - i >= i) // 优化 30 { 31 r += (j-i)/i; 32 j -= (j-i)/i*i; 33 } else if(j - i < i) { 34 r++; 35 j = j - i; 36 } 37 } 38 } 39 printf("Scenario #%lld:\n%lld %lld\n\n",++cnt,l,r); // 按要求输出 40 } 41 return 0; 42 }

浙公网安备 33010602011771号