Description
Background
Binary trees is a common data structure in computer. In this problem we'll look at an infinite binary tree where the nodes contain a pair of integers. The tree is a constructed like this:
- The root contains the pair (1, 1).
- If a node contains (a, b) then it left child contains (A + B, b) and its right child (a, A + B)
problem
Given the contents (A, B) of some node of the binary tree described above, suppose you is walking from the root of the TR EE to the given node along the shortest possible path. Can you find out what often you has to go to a left child and what often to a right child?
Input
The first line contains the number of scenarios.
Every scenario consists of a single line containing II integers I and j (1 <= I, J <= 2*109) that represent
A node (i, J). You can assume the valid node in the binary tree described above.
Output
The output for every scenario begins with a line containing "scenario #i:", where I am the number of the scenario starting at 1. Then print a single line containing the numbers L and R separated by a single space, where L was how often you had to go l EFT and R is what often you has 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
342 13 417 73
Sample Output
Scenario #1:0Scenario #2:2 1Scenario #3:4 6
Source
TUD Programming Contest 2005 (Training Session), Darmstadt, Germany
This title is a two-fork tree, in fact, is mainly a mathematical method to accelerate the calculation.
The most simple idea is to find from the target node to the root node, then the efficiency is equal to the tree height;
However, because the tree height may be great, so the lookup will time out.
Then in the search for the root node, the topic of the +-law into a division search, you can greatly accelerate the search, from the original time-out to 0ms.
#include <stdio.h>int main () {int T, A, B, LC, RC, T = 1;scanf ("%d", &t), while (t--) {scanf ("%d%d", &a, & b) rc = LC = 0;while (A! = 1 | | b! = 1) {if (a > B) {int c = a/b;a%= b;//because it is legal and therefore only b==1, it is possible a==0if (!a)--c, a = 1;//last a ==0 when you want to correct the results LC + = C;} Else{int C = b/a;b%= a;if (!b)--c, b = 1;rc + = C;}} printf ("Scenario #%d:\n%d%d\n\n", t++, LC, RC);} return 0;}
Mathematical puzzle of POJ 2499 Binary Tree