POJ 2499 Binary Tree 数学题解

Description

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: 
  • The root contains the pair (1, 1). 
  • If a node contains (a, b) then its 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 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*10 9) 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

Source

TUD Programming Contest 2005 (Training Session), Darmstadt, Germany

本题名为二叉树,其实主要是考数学加速计算的方法。

本题思路最简单就是从目标节点往根节点查找,那么效率就等于树高了;

不过由于树高可能会极大,故此这样查找会超时。

那么就在查找根节点的时候,把题目的+-法变成除法查找,就可以极大加速查找了,由原来的超时变成0ms过了。


#include 
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;//因为合法,故此只有b==1,有可能a==0
				if (!a) --c, a = 1;//最后a==0的时候要修正结果
				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;
}



你可能感兴趣的:(Algorithm算法)