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]);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值