Binary Tree
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
太棒了,竟然写对了哎。
import java.util.Scanner;
class Test48{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N =sc.nextInt();
for(int i=0;i<N;i++){
int m = sc.nextInt();
int n =sc.nextInt();
f(m,n);
System.out.printf("Scenario #"+(num++)+":");
System.out.println();
System.out.printf("%d %d",c_l,c_r);
System.out.println();
c_l = 0;
c_r = 0;
}
}
static int num =1;
static int c_l =0;
static int c_r= 0;
static void f(int m,int n){
if(m>n){
c_l++;
if(!((m-n)==1)||!(n==1)){
f((m-n),n);
}
}else {
c_r++;
if(!((m-n)==1)||!(n==1)){
f(m,n-m);
}
}
}
}
这个是优化
用除法代替减法,得到的商即为往左走的次数,最后的m=m%n。 42 n>m时情况类推。 43 需要特别注意的是: 44 如果m>n,m%n == 0 怎么办?因为根(1,1)不可能有0存在,所以特殊处理一下: 45 次数:m/n-1;m=1
import java.util.Scanner;
class Test48{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N =sc.nextInt();
for(int i=0;i<N;i++){
int m = sc.nextInt();
int n =sc.nextInt();
f(m,n);
System.out.printf("Scenario #"+(num++)+":");
System.out.println();
System.out.printf("%d %d",c_l,c_r);
System.out.println();
c_l = 0;
c_r = 0;
}
}
static int num =1;
static int c_l =0;
static int c_r= 0;
static void f(int m,int n){
// if(m>n){
//
// c_l++;
// if(!((m-n)==1)||!(n==1)){
// f((m-n),n);
// }
// }else {
//
// c_r++;
// if(!((m-n)==1)||!(n==1)){
// f(m,n-m);
// }
// }
while (m!=1|| n!=1){
if(m>=n){
if(m%n!=0){
c_l+=m/n;
m = m%n;
}
else {
c_l = m/n-1;
m = 1;
}
}
else {
if(n%m!=0){
c_r+=n/m;
n= n%m;
}
else {
c_r = n/m-1;
n = 1;
}
}
}
}
}
不知道为啥,第三个案例没有过,代码可能有一点小小的问题。
参考:https://www.cnblogs.com/dongsheng/archive/2013/03/03/2942067.html