Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
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
Solution
題目的意思是找出有多少個連續的0,就是找規律看看。
n=1 ---------> 01 --------> 0
n=2 ---------> 1001 --------> 1
n=3 ---------> 01101001 --------> 1
n=4 ---------> 1001011001101001 --------> 3
n=5 ---------> 01101001100101101001011001101001 --------> 5
算着的時候,我就發現0*2+1 = 1, 1*2-1 = 1, 1*2+1 = 3, 3*2-1 = 5,蠻符合的,就推論n=6的時候爲5*2+1 = 11,發現沒錯。
於是就得出了f(n) = f(n-1)*2 + (-1)^n,注意n有1000之大,所以要用高精度乘法,每次乘最多進一位,於是位數最多也就1000,敲出來就A啦
(PS:其實加一減一是看一下前一個序列首尾是否相同的時候,列表並綜合結果發現的)
#include <iostream>
#include <cstring>
using namespace std;
int ans[1005][1005];//高精度乘法的結果數組
int main()
{
int i, j, n;
memset(ans, 0, sizeof(ans));
ans[1][0] = 0;
for (int i = 2; i < 1005; ++i)//簡單粗暴的乘法,可以優化的
{
for (j = 0; j < 1005; ++j) ans[i][j] = ans[i-1][j] * 2;
if (i%2) ans[i][0] -= 1;//處理加一減一
else ans[i][0] += 1;
for (j = 0; j < 1005; ++j) if (ans[i][j] > 9)
{
ans[i][j+1] += ans[i][j] / 10;
ans[i][j] %= 10;
}
}
while (cin >> n)
{
i = 1004;
while (ans[n][i] == 0 && i > 0) --i;//輸出0的時候的控制
while (i >= 0) cout << ans[n][i--];
cout << endl;
}
return 0;
}