HDU1041 Computer Transformation(java)

Problem Description
A sequence consisting of one digit, the number 1 is initially written into a computer. At each successive time step, the computer simultaneously tranforms each digit 0 into the sequence 1 0 and each digit 1 into the sequence 0 1. So, after the first time step, the sequence 0 1 is obtained; after the second, the sequence 1 0 0 1, after the third, the sequence 0 1 1 0 1 0 0 1 and so on.

How many pairs of consequitive zeroes will appear in the sequence after n steps?

Input
Every input line contains one natural number n (0 < n ≤1000).

Output
For each input n print the number of consecutive zeroes pairs that will appear in the sequence after n steps.

Sample Input
2
3

Sample Output
1
1
題意是每步中將1變成01,0變成10,初始數字爲1,求n步後結果串中有多少對00。
1
Step1:01。
Step2:1001。
Step3:01101001。
Step4:1001011001101001。
分析過程我們可以知道第n個串中的00來源有兩個部分:
1.第n-2個串
2.第n-2個串中1的格式(1經過兩步後變爲1001)。
所以有有遞推公式C(n)=C(n-2)+2^(n-3) 其中n>=4

import java.math.BigInteger;
import java.util.Scanner;

/**
 * 
 * @author  Jackie
 *  date    2015年10月22日
 *  desc    ACM
 *  C(n)=C(n-2)+2^(n-3) 其中n>=4
 */
public class P1041 {

    public static BigInteger[] midRes = new BigInteger[1001];
    public static BigInteger[] result = new BigInteger[1001];
    public static void main(String[] args) {
        new P1041().run();
    }

    public void run(){
        initial();
        Scanner scanner = new Scanner(System.in);
        int n;
        while (scanner.hasNextInt()) {
            n = scanner.nextInt();
            System.out.println(result[n]);
        }
        scanner.close();
    }

    public void initial(){
        result[1] = BigInteger.valueOf(0);
        result[2] = BigInteger.valueOf(1);
        result[3] = BigInteger.valueOf(1);

        midRes[0] = BigInteger.valueOf(1);
        midRes[1] = BigInteger.valueOf(2);
        midRes[2] = BigInteger.valueOf(4);
        midRes[3] = BigInteger.valueOf(8);


        for (int i = 4; i <= 1000; i++) {
            /**
             *沒有考慮到2^(i - 3)也是一個大數,使用long強制轉換後會是遠離值縮小
             *所以可以使用一個大數數組存儲中間值2^(i - 3);
             */
//          result[i] = result[i - 2].add(BigInteger.valueOf((long) Math.pow(2, i - 3)));
            /**
             *正確使用遞推公式的方法
             */
            midRes[i] = midRes[i - 1].multiply(BigInteger.valueOf(2));
            result[i] = result[i - 2].add(midRes[i - 3]);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章