Rational Number Tree

转载请注明来自souldak,微博:@evagle

Google of Greater China Test for New Grads of 2014 Round A 第2题,题目: Rational Number Tree

如下面这颗树,生成规则是,左儿子的分子和父节点一样,分母是父节点分子分母之和,右儿子的分母和父节点一样,分子是父节点分子分母之和。

这个数按层遍历得到一个序列:1/1, 1/2, 2/1 , 1/3 , 3/2, 2/3 , 3/1....

1. 现在给定其中一项,然后求出这一项在这个序列中排第几

2. 求序列的第n项,例如第二项是1/2

         1/1
    ______|______
    |           |
   1/2         2/1
 ___|___     ___|___
 |     |     |     |
1/3   3/2   2/3   3/1

我们先构造另一颗二进制树,

                 1

       10            11

100   101   110   111

....

即左儿子是父节点序列后面加0,右儿子是父节点序列加1,如果按层遍历然后转换成十进制数,正好是1,2,3,4,5,6,7,..... 所以这个树的值就是按层遍历时候它所在的项的位置。把两棵树结合在一起考虑,将它们的节点一一对应,那给定任何一项,我们只要找到二进制树中对应值就可以得到它是第几项了,现在怎么找呢?

看对应关系,假设父节点p/q, 题目给的树左儿子为p/(p+q),p<p+q, 右儿子,(p+q)/q,p+q>q, 所以给定m/n,如果m>n,则是父节点的右儿子,否则是父节点的左儿子。如果是右儿子,那最后一位对应1,如果是左儿子,最后一位对应0。然后求父节点,根据规则反推即可,如果是左儿子m/(n-m), 如果是右儿子,(m-n)/n。然后递归往上推,直到遇到1/1 结束,1/1是根节点对应的二进制1。其中产生的0,1串就是位置了。

例如求2/3

起始     左儿子还是右儿子   最后一位二进制     父节点

2/3                左                              0                           2/(3-2)

2/1                右                              1                           (2-1)/1

1/1                根节点                      1

这样就得到二进制110,所以它是第6项

复杂度是O(log(n)),n是第几项


同理如果要求出第n项的值,先将n转为二进制,然后去掉最高位的1(因为它对应根节点1/1),然后如果是0,往左走,计算左儿子,如果是1,计算右儿子。循环一直走完所有的二进制位结束,得到的节点就是答案。

例如求第5项,11=1011,第一个1对应的是1/1

二进制位          往左或往右       父节点      节点

   1                                                                   1/1

   0                           左                   1/1            1/2

   1                           右                   1/2            3/2

   1                           右                   3/2            5/2

所以第11项对应的是5/2

复杂度是O(log(n))

因为n最大是2^64,如果用C++ ,一定要用unsigned long long,java没有这个类型,只能用BigInteger

package rounda;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Scanner;

public class Problem3 {
	public void input(Scanner scanner) {

	}

	public void output(int caseNo, FileOutputStream fop) {

	}
 

	public Node walk(Node father, boolean orient) {
		if (!orient ) {
			return new Node(father.p,father.p.add(father.q));
			 
		}else{
			return new Node(father.p.add(father.q),  father.q);
		}
	}

	class Node {
		public BigInteger p;
		public BigInteger q;
		public Node(BigInteger p,BigInteger q){
			this.p = p;
			this.q=q;
		}
		Node(){
			
		}
	}
	public  Node solve(BigInteger n){
		if(n.compareTo(new BigInteger("1"))==0)
			return new Node(new BigInteger("1"),new BigInteger("1"));
		int maxbit=0;
		for(int i=63;i>=0;i--){
			if(n.testBit(i)){
				maxbit=i;
				break;
			}
		}
		Node node =  new Node(new BigInteger("1"),new BigInteger("1"));
		for(int i=maxbit-1;i>=0;i--){
			node = walk(node,n.testBit(i));
		}
		return node;
	}
	public BigInteger solve(BigInteger p,BigInteger q){
		Node node = new Node(p,q);
		String s ="";
		while(true){
			if(node.p.compareTo(node.q)>0){
				s+="1";
				node.p = node.p.subtract(node.q);
			}else{
				s+="0";
				node.q = node.q.subtract(node.p);
			}
			if(node.p.compareTo(new BigInteger("1"))==0&&
					node.q.compareTo(new BigInteger("1"))==0){
				break;
			}
		}
		s+="1";
		s = new StringBuilder(s).reverse().toString();
		BigInteger res = new BigInteger("0");
		for(int i=0;i<s.length();i++){
			res = res.multiply(new BigInteger("2")).add(new BigInteger((s.charAt(i)-'0')+""));
		}
		return res;
	}
	public static void main(String[] args) {
		Scanner scanner;
		Problem3 pr = new Problem3();
		scanner = new Scanner(System.in);
		int T = scanner.nextInt();
		int count = T;
		while (count-- > 0) {
			int type = scanner.nextInt();
			if (type == 1) {
				BigInteger n = new BigInteger(scanner.next());
				Node res = pr.solve(n);
				System.out.println("Case #"+(T-count)+": "+res.p+" "+res.q);
			}else{
				BigInteger p = new BigInteger(scanner.next());
				BigInteger q = new BigInteger(scanner.next());
				BigInteger res = pr.solve(p,q);
				System.out.println("Case #"+(T-count)+": "+res);
			}
		}

	}

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
(Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations: a. Add two Rational numbers: The result of the addition should be stored in reduced form. b. Subtract two Rational numbers: The result of the subtraction should be stored in reduced form. c. Multiply two Rational numbers: The result of the multiplication should be stored in reduced form. d. Divide two Rational numbers: The result of the division should be stored in reduced form. e. Print Rational numbers in the form a/b, where a is the numerator and b is the denominator. f. Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.) – 提示: – 有理数是有分子、分母以形式a/b表示的数,其中a是分子,b是分母。例如,1/3,3/4,10/4。 – 有理数的分母不能为0,分子却可以为0。每个整数a等价于有理数a/1。有理数用于分数的精确计算中。例如1/3=0.0000…,它不能使用数据类型double或float的浮点格式精确表示出来,为了得到准确结果,必须使用有理数。 – Java提供了整数和浮点数的数据类型,但是没有提供有理数的类型。 – 由于有理数与整数、浮点数有许多共同特征,并且Number类是数字包装的根类,因此,把有理数类Rational定义为Number类的一个子类是比较合适的。由于有理数是可比较的,那么Rational类也应该实现Comparable接口。+下页图中描述了Rational类已将其与Number类和Comparable接口的关系。 –
8.17 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 1/2 and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations: a. Add two Rational numbers: The result of the addition should be stored in reduced form. b. Subtract two Rational numbers: The result of the subtraction should be stored in reduced form. c. Multiply two Rational numbers: The result of the multiplication should be stored in reduced form. d. Divide two Rational numbers: The result of the division should be stored in reduced form. e. Print Rational numbers in the form a/b, where a is the numerator and b is the denominator. f. Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.) – 提示: – 有理数是有分子、分母以形式a/b表示的数,其中a是分子,b是分母。例如,1/3,3/4,10/4。 – 有理数的分母不能为0,分子却可以为0。每个整数a等价于有理数a/1。有理数用于分数的精确计算中。例如1/3=0.0000…,它不能使用数据类型double或float的浮点格式精确表示出来,为了得到准确结果,必须使用有理数。 – Java提供了整数和浮点数的数据类型,但是没有提供有理数的类型。 – 由于有理数与整数、浮点数有许多共同特征,并且Number类是数字包装的根类,因此,把有理数类Rational定义为Number类的一个子类是比较合适的。由于有理数是可比较的,那么Rational类也应该实现Comparable接口。
下面是一个简单的实现RationalNumber类的C++代码: ```c++ #include <iostream> using namespace std; class RationalNumber { private: int numerator; // 分子 int denominator; // 分母 public: RationalNumber() { numerator = 0; denominator = 1; } RationalNumber(int numerator, int denominator) { this->numerator = numerator; this->denominator = denominator; simplify(); // 约分 } // 获取分子 int getNumerator() const { return numerator; } // 获取分母 int getDenominator() const { return denominator; } // 赋值运算符重载 RationalNumber& operator=(const RationalNumber& other) { if (this != &other) { numerator = other.numerator; denominator = other.denominator; } return *this; } // 加法运算符重载 RationalNumber operator+(const RationalNumber& other) { int newNumerator = numerator * other.denominator + other.numerator * denominator; int newDenominator = denominator * other.denominator; return RationalNumber(newNumerator, newDenominator); } // 减法运算符重载 RationalNumber operator-(const RationalNumber& other) { int newNumerator = numerator * other.denominator - other.numerator * denominator; int newDenominator = denominator * other.denominator; return RationalNumber(newNumerator, newDenominator); } // 乘法运算符重载 RationalNumber operator*(const RationalNumber& other) { int newNumerator = numerator * other.numerator; int newDenominator = denominator * other.denominator; return RationalNumber(newNumerator, newDenominator); } // 除法运算符重载 RationalNumber operator/(const RationalNumber& other) { int newNumerator = numerator * other.denominator; int newDenominator = denominator * other.numerator; return RationalNumber(newNumerator, newDenominator); } // 约分 void simplify() { int gcd = getGCD(numerator, denominator); numerator /= gcd; denominator /= gcd; if (denominator < 0) { numerator *= -1; denominator *= -1; } } // 获取最大公约数 int getGCD(int a, int b) { if (b == 0) { return a; } return getGCD(b, a % b); } // 输出有理数 void print() const { if (denominator == 1) { cout << numerator << endl; } else { cout << numerator << "/" << denominator << endl; } } }; int main() { RationalNumber r1(2, 3); RationalNumber r2(3, 4); RationalNumber r3 = r1 + r2; RationalNumber r4 = r1 - r2; RationalNumber r5 = r1 * r2; RationalNumber r6 = r1 / r2; cout << "r1 = "; r1.print(); cout << "r2 = "; r2.print(); cout << "r1 + r2 = "; r3.print(); cout << "r1 - r2 = "; r4.print(); cout << "r1 * r2 = "; r5.print(); cout << "r1 / r2 = "; r6.print(); return 0; } ``` 在该代码中,定义了一个 `RationalNumber` 类,包含了分子和分母两个私有成员变量,以及一些公有成员函数,包括构造函数、赋值运算符重载、加法、减法、乘法、除法运算符重载、约分、获取最大公约数、输出有理数等。在 `main` 函数中,创建了两个有理数对象 `r1` 和 `r2`,并对其进行了加、减、乘、除等运算,最后输出了结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值