(a,a+b)

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)

Problem 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*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

 

其实就是贪心,从结点开始一直相减就可以了,但是有时间限制,优化下就ok,比如1和10000000,相差的倍数很大,也就是一个数减去里一个数的n-1倍,就轻松accept了

 1 #include<iostream>
 2 using namespace std;
 3 
 4 void so(int x,int y,int &left,int &right)
 5 {
 6     while(!(x==1&&y==1))
 7     {
 8     if(x>y)
 9     {
10         if(x/y>2)
11         {
12             int temp=x/y;
13             x=x-(x/y-1)*y;
14             left+=(temp-1);
15         }
16         else
17         {
18             x-=y;
19             left++;
20         }
21     }
22     else
23     {
24         if(y/x>2)
25         {
26             int temp=y/x;
27             y=y-(y/x-1)*x;
28             right+=(temp-1);
29         }
30         else
31         {
32             y-=x;
33             right++;
34         }
35     }
36     }
37 }
38 
39 
40 int main()
41 {
42     int n,i,j,x,y;
43     cin>>n;
44     for(i=0;i<n;i++)
45     {
46         cin>>x>>y;
47         int left=0;
48         int right=0;
49         cout<<"Scenario #"<<i+1<<":"<<endl;
50         so(x,y,left,right);
51         cout<<left<<" "<<right<<endl;
52         if(i!=n-1)
53             cout<<endl;
54     }
55     return 0;
56 }
posted @ 2012-10-26 23:56  zerojetlag  阅读(287)  评论(0编辑  收藏  举报