1sting(斐波那契數列、模擬加法)
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; }