杭电oj HDOJ 1041 Computer Transformation
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1041
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.
题目大意
刚开始一个数列中只有一个数1,然后按照把1变成01、把0变成10的规则逐步地变换下去,现求当变换了n步后数列中“00”子列的数量。
解题思路
题中出现“00”时,一定是在“1001”中得到的,而n步中的“1001”是由n-1步中的“01”得到的,进一步,是由n-2步中的“1”得到的,列出前几项的变换结果可以得出“00”数量的递推公式,设res[n]为变换n步后数列中“00”的数量,则
r
e
s
[
n
]
=
r
e
s
[
n
−
1
]
+
2
×
r
e
s
[
n
−
2
]
res[n]=res[n-1]+2\times res[n-2]
res[n]=res[n−1]+2×res[n−2]由于本题中数列的数字个数按指数级增长,所以数据量非常大,连__int64
也无法表示完全,所以要用一个二位数组来进行递推的计算。
本人的C++解决方案
#include <iostream>
#include <stdio.h>
using namespace std;
int res[1000][400];
int main()
{
int n, i, j, temp;
res[0][0] = 0;
res[1][0] = 1;
for (i = 2; i < 1000; i++) {
temp = 0;
for (j = 0; j < 400; j++) {
res[i][j] = res[i - 1][j] + 2 * res[i - 2][j] + temp;
temp = res[i][j] / 10;
res[i][j] %= 10;
}
}
while (cin >> n) {
if (n == 1) {
printf("%d\n", 0);
}
else {
// 确定开始位置
for (i = 399; i >= 0; i--) {
if (res[n - 1][i]) {
break;
}
}
// 倒叙输出
for (; i >= 0; i--) {
printf("%d", res[n - 1][i]);
}
printf("\n");
}
}
}
代码通过HDOJ平台运行通过,如发现错误,欢迎指出和纠正,谢谢!