Problem Description
A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
Input
Each line will contain an integers. Process to end of file.
Output
For each case, output the result in a line.
Sample Input
100
Sample Output
4203968145672990846840663646
这个题在两个时间去做的,第一次是的代码
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 using namespace std; 6 int dp[8001][2301]; 7 int main() 8 { 9 int len,sum; 10 memset(dp,0,sizeof(dp)); 11 dp[1][2300]=dp[2][2300]=dp[3][2300]=dp[4][2300]=1; 12 len=1; 13 for(int i=5;i<8001;i++) 14 { 15 sum=0; 16 for(int j=2300;j>2300-len;j--) 17 { 18 sum+=dp[i-1][j]+dp[i-2][j]+dp[i-3][j]+dp[i-4][j]; 19 dp[i][j]=sum%10; 20 sum/=10; 21 while(j==2300-len+1&&sum>0) 22 { 23 dp[i][2300-len]=sum; 24 len++; 25 break; 26 } 27 } 28 } 29 int n; 30 while(cin>>n) 31 { 32 int t; 33 for(t=0;t<2300;t++) 34 if(dp[n][t]!=0) 35 break; 36 for(int j=t;j<=2300;j++) 37 cout<<dp[n][j]; 38 cout<<endl; 39 } 40 return 0; 41 }
但是一直(Memory Limit Exceeded)就看了大神的代码
1 #include <iostream> 2 #include <cstdio> 3 #include <vector> 4 #include <algorithm> 5 #include <cmath> 6 #include <string.h> 7 #include <malloc.h> 8 using namespace std; 9 void add(char *a,char *b,char *c) 10 { 11 int i,j,k,t,lmax,lmin,tmp; 12 char *s,*pmax,*pmin; 13 lmax=strlen(a); 14 lmin=strlen(b); 15 if(lmax<lmin) 16 { 17 tmp=lmax;lmax=lmin;lmin=tmp; 18 pmax=b;pmin=a; 19 } 20 else 21 { 22 pmax=a;pmin=b; 23 } 24 s=(char*)malloc(sizeof(char)*(lmax+1)); 25 s[0]='0';//注意此处很容易被忽略 26 for(i=lmax-1,j=lmin-1,k=lmax;j>=0;i--,j--,k--) 27 s[k]=pmax[i]-'0'+pmin[j]; 28 for(;i>=0;i--,k--) 29 s[k]=pmax[i]; 30 for(i=lmax;i>=0;i--) 31 if(s[i]>'9') 32 { 33 s[i]-=10; 34 s[i-1]++; 35 } 36 if(s[0]=='0') 37 { 38 for(i=0;i<=lmax;i++) 39 c[i-1]=s[i]; 40 c[i-1]='