POJ 2499 Binary Tree

来源:互联网 发布:道路测量员软件说明书 编辑:程序博客网 时间:2024/05/04 20:58

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

Copy sample input to clipboard

 342 13 417 73

Sample Output

Scenario #1:41 0Scenario #2:2 1Scenario #3:4 6

个人想法

今天开始每天要写一篇算法题博客,好好刷题,但是遇到第一题就不太会做,经过网上查资料后,发现大家都是从后往前推导,这样会简单很多,在纸上演绎时,发现确实如此。为什么会这样呢?经过和舍友的讨论后想起,树的定义就是只有一个前驱元,所以这个结果肯定只有一个父节点,但是会有两个子节点的可能,所以从后往前推导会简单很多。

#include <iostream>using namespace std;int main(void){    int count;      cin>>count;    for(int i=0;i<count;++i){        int a,b;        cin>>a>>b;        int left=0,right=0;        while(a!=1&&b!=1){            if(a<b){                right+=b/a;                b%=a;            }            else if(a>b){                left+=a/b;                a%=b;            }        }        if(a!=1){            left+=(a/b-1);        }        else if(b!=1){            right+=(b/a-1);        }        cout<<"Scenario #";        cout<<i+1<<":"<<endl;        cout<<left<<" "<<right<<endl;       }    return 0;}
原创粉丝点击