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]);
}
}
}