Computer Transformation
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8410 Accepted Submission(s): 3161
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?
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
由于a[n]的1001是由前一次(即a[n-1])的01变化而成,而a[n-1]的01由a[n-2]的1和1001构成,
a[n-2]的1001数目即a[n-2],而1的数量一直是呈2的倍数增长,a[n-2]的1的数量是a[n-3]
于是有a[n]=2^(n-3)+a[n-2];
以下是递推为更简单的形式过程
2^(n-3)=a[n]-a[n-2];
2^(n-2)=a[n+1]-a[n-1];
相减
a[n+1]=2*a[n]+a[n-1]-2*a[n-2];
即:
a[n]=2*a[n-1]+a[n-2]-2*a[n-3]
=a[n-1]+2*a[n-2]+a[n-1]-a[n-2]-2*a[n-3]
有
a[n]-a[n-1]-2*a[n-2]=a[n-1]-a[n-2]-2*a[n-3]
都等于零
于是a[n]=a[n-1]+2*a[n-2];
#include <bits/stdc++.h>
using namespace std;
string a[1009];
string add1(string s1, string s2)
{
if (s1 == "" && s2 == "") return "0";
if (s1 == "") return s2;
if (s2 == "") return s1;
string maxx = s1, minn = s2;
if (s1.length() < s2.length()){
maxx = s2;
minn = s1;
}
int a = maxx.length() - 1, b = minn.length() - 1;
for (int i = b; i >= 0; --i){
maxx[a--] += minn[i] - '0'; // a一直在减 , 额外还要减个'0'
}
for (int i = maxx.length()-1; i > 0;--i){
if (maxx[i] > '9'){
maxx[i] -= 10;//注意这个是减10
maxx[i - 1]++;
}
}
if (maxx[0] > '9'){
maxx[0] -= 10;
maxx = '1' + maxx;
}
return maxx;
}
int main()
{
a[1]="0",a[2]="1",a[3]="1",a[4]="3";
for(int i=5;i<=1004;i++){
a[i]=add1(add1(a[i-2],a[i-2]),a[i-1]);
}
int n;
while(cin>>n){
cout<<a[n]<<endl;
}
return 0;
}