Description
You will be given a string which only contains ‘1’; You can merge two adjacent ‘1’ to be ‘2’, or leave the ‘1’ there. Surly, you may get many different results. For example, given 1111 , you can get 1111, 121, 112,211,22. Now, your work is to find the total number of result you can get.
Input
The first line is a number n refers to the number of test cases. Then n lines follows, each line has a string made up of ‘1’ . The maximum length of the sequence is 200.
Output
The output contain n lines, each line output the number of result you can get .
Sample Input
3 1 11 11111
Sample Output
1 2 8
本题的规律是斐波那契数列,在这里就不细说了。斐波那契数列的增长速度非常快,long long的数据类型也很快就会放不下,如何表示斐波那契数列是本题的关键。在这里就需要用到数组来模拟加法,分别将两个数的每一位取出放到两个数组中,在以此将两个数组对应的数加起来。为了解决进位的问题,我们可以将数倒着存入数组中,然后从最低位开始相加,如果遇到进位就让数组中前一个数+1,自己本身与10取余。代码如下:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int num[220][1000];
num[1][1]=1;
num[2][1]=2;
for(int i=3;i<=200;i++)
{
for(int j=1;j<1000;j++)
{
num[i][j]+=num[i-1][j]+num[i-2][j];
if(num[i][j]>=10)
{
num[i][j+1]++; //进位操作
num[i][j]%=10; //自己本身要与10取余
}
}
}
int n;
cin>>n;
while(n--)
{
char a[25];
cin>>a;
int len=strlen(a);
int i;
for(i=999;i>0 && num[len][i]==0;i--);
for(;i>0;i--)
cout<<num[len][i];
cout<<endl;
}
return 0;
}