HDU - 1250 Hat's Fibonacci (大数+滚动数组)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chimchim04/article/details/88833184

Hat's Fibonacci

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.

题目大意:

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)

求 F(n)  结果的位数不超过2005位;

思路:比赛的时候首先想到大数加法 打表,开了个7005*2010 的数组存,然后很明显就爆内存了,然后就是没想到要用滚动数组,一直在死磕,疯狂试探内存边界,最后当然还是不行。然后就想着换一种存储方式,然后改用string。修修改改之后终于没爆内存,但是WA了,最后没时间了。然后结束之后才知道要用滚动数组。然后直接用大数和滚动数组交了一发,超时了。。。

直接10进位的话会超时,我改成了10000进位,时间会短一些,然后终于过了。

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=2050;
const int mod=1e4;
int a[5][N];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        if(n<=4)
        {
            printf("1\n");
            continue;
        }
        memset(a,0,sizeof(a));
        a[1][0]=a[2][0]=a[3][0]=a[0][0]=1;
        int cnt=3,len=0;
        for(int i=4;i<n;i++)
        {
            cnt=(cnt==4?0:cnt+1);
            memset(a[cnt],0,sizeof(a[cnt]));
            for(int j=1;j<5;j++)
            {
                int tmp=(cnt+j>=5?cnt+j-5:cnt+j);
                for(int k=0;k<=len;k++)
                {
                    a[cnt][k]+=a[tmp][k];
                    if(a[cnt][k]>mod)
                    {
                        a[cnt][k+1]+=a[cnt][k]/mod;
                        a[cnt][k]%=mod;
                    }
                }
                if(a[cnt][len]) len++;
            }
        }
        printf("%d",a[cnt][len-1]);
        for(int i=len-2;i>=0;i--)
            printf("%04d",a[cnt][i]);
        printf("\n");
    }
    return 0;
}


 

猜你喜欢

转载自blog.csdn.net/chimchim04/article/details/88833184