Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13827 Accepted Submission(s): 4638
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.
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
Note: No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
考察高精度运算,后面有给出限制条件,位数不能超过2005位。
直接模拟可以做出来
#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<iostream>
using namespace std;
const int maxn=10000;
const int inf=0x3f3f3f3f;//最大值
short int b[7010][2005];
short int changdu[7400];
int main()
{
int t;
b[1][1]=1;
b[2][1]=1;
b[3][1]=1;
b[4][1]=1;
changdu[1]=changdu[2]=changdu[3]=changdu[4]=1;//代表长度是1
int changduu=1;
for(int i=5;i<=7010;++i)
{
int jinwei=0;
for(int j=1;j<=changdu[i-1];++j)
{
b[i][j]=(b[i-1][j]+b[i-2][j]+b[i-3][j]+b[i-4][j]+jinwei)%10;
jinwei=(b[i-1][j]+b[i-2][j]+b[i-3][j]+b[i-4][j]+jinwei)/10;
}
changdu[i]=changdu[i-1];
if(jinwei!=0)
{
changdu[i]++;
b[i][changdu[i]]=jinwei;
}
}
while(~scanf("%d",&t))
{
for(int i=changdu[t];i>=1;--i)
printf("%d",b[t][i]);
printf("\n");
}
return 0;
}
short int 2个字节
int 2/4字节
long 4/8字节
long long 8字节
这道题有卡数据,如果直接使用int的话,会内存超限,需要使用short int
也可以使用结构体大数:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<vector>
#include<map>
using namespace std;
struct BigInt
{
const static int mod=10000;
const static int DLEN=4;
int a[500],len;
BigInt(){
memset(a,0,sizeof(a));
len=1;
}
BigInt(int v){
memset(a,0,sizeof(a));
len=0;
do
{
a[len++]=v%mod;
v/=mod;
}while(v);
}
BigInt(const char s[]){
memset(a,0,sizeof(a));
int L=strlen(s);
len=L/DLEN;
if(L%DLEN) len++;
int index=0;
for(int i=L-1;i>=0;i-=DLEN)
{
int t=0;
int k=i-DLEN+1;
if(k<0) k=0;
for(int j=k;j<=i;++j)
{
t=t*10+s[j]-'0';
}
a[index++]=t;
}
}
BigInt operator+(const BigInt &b)const{
BigInt res;
res.len=max(len,b.len);
for(int i=0;i<=res.len;++i)
res.a[i]=0;
for(int i=0;i<res.len;++i)
{
res.a[i]+=((i<len)?a[i]:0)+((i<b.len)?b.a[i]:0);
res.a[i+1]+=res.a[i]/mod;
res.a[i]%=mod;
}
if(res.a[res.len]>0) res.len++;
return res;
}
void output(){
printf("%d",a[len-1]);
for(int i=len-2;i>=0;--i)
printf("%04d",a[i]);
printf("\n");
}
};
BigInt f[7100];
int main()
{
BigInt mid(1);
f[1]=f[2]=f[3]=f[4]=mid;
int n;
for(int i=5;i<7099;++i){
f[i]=f[i-1]+f[i-2]+f[i-3]+f[i-4];
}
while(~scanf("%d",&n)){
f[n].output();
}
}