Binary Tree(生成二叉树)

时间:2024-04-18 20:33:37

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
题目意思:当时一看题目确实被吓到了,以为真的是数据结构中的二叉树,毕竟作为一个萌新acmer,真真被唬住了。
看了看样例其实和二叉树没有太大关系,我们知道二叉树的根节点是(1,1),题目给一个(l,r)求其回到(1,1)
向左向右转的次数。
解题思路:我们先来考虑一下(l,r)的来源,因为r!=l,若l>r,那么(l,r)来自于(l-r,r)向左转;若r>l,
那么(l,r)来自于(l,r-l)向右转。那么可以通过递推的不断相减得到以下的代码:
 #include<stdio.h>
#include<string.h>
int main()
{
int t;
long long a,b,m,n,lcount,rcount,i;
scanf("%d",&t);
i=;
while(t--)
{
scanf("%lld%lld",&a,&b);
lcount=;
rcount=;
while()
{
if(a>b)
{
a=a-b;
lcount++;
}
if(b>a)
{
b=b-a;
rcount++;
}
if(b==&&a==)
break;
}
printf("Scenario #%lld:\n",i++);
printf("%lld %lld\n\n",lcount,rcount);
}
return ;
}

很不幸的是交上之后直接时间超限,再看看题 two integers i and j (1 <= i, j <= 2*10 9),都达到了数亿的数量级,显然会造成数亿次的常数

运算,那么就需要换换思路了,我参考了一下网上大佬们的算法,运用除法来代替减法实现加速运算,这种思路其实在之前的某些题目中

运用过。

上代码:

 #include<stdio.h>
#include<string.h>
int main()
{
int t;
long long a,b,c,m,n,lcount,rcount,i;
scanf("%d",&t);
i=;
while(t--)
{
scanf("%lld%lld",&a,&b);
lcount=;
rcount=;
while()
{
if(a>b)
{
c=a/b;
a=a%b;///当b==1时,有可能造成a==0
if(a==)///此时需要调成结果
{
c--;
a=;
}
lcount=lcount+c;
}
if(b>a)
{
c=b/a;
b=b%a;
if(b==)
{
c--;
b=;
}
rcount=rcount+c; }
if(b==&&a==)
break;
}
printf("Scenario #%lld:\n",i++);
printf("%lld %lld\n\n",lcount,rcount);
}
return ;
}

不得不感慨,还是得学习啊。