杭电ACM 1250 Hat's Fibonacci (还需再看)

来源:互联网 发布:唱谱软件安卓版 编辑:程序博客网 时间:2024/06/08 04:47

                                                        Hat's Fibonacci

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
4203968145672990846840663646Note:No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
 

注意:本题和其他大数不同的是在计算大数相加的结果时,数组的每一位要存放10000,而不是10,因为存10会超内存

AC代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define M 7250
int fib[M][600];
void fibonacci()
{   
 //memset(fib,0,sizeof(fib));
     int i,j;
     fib[0][0]=0;
     fib[1][0]=1;
     fib[2][0]=1;
     fib[3][0]=1;
     fib[4][0]=1;
     for(i=5;i<7200;i++)
     {
     for(j=0;j<600;j++)
  {
     fib[i][j]=fib[i][j]+fib[i-1][j]+fib[i-2][j]+fib[i-3][j]+fib[i-4][j];//将该位上的数和上面四个数该位上的数相加来计算结果
  fib[i][j+1]=fib[i][j+1]+fib[i][j]/10000;//每一位上面要存10000,刚开始我每一位都存的是10,会超内存
     fib[i][j]=fib[i][j]%10000;
     }
     }
}
int main()
{
    int n,i;
    fibonacci();
    while(scanf("%d",&n)!=EOF)
    {
    if(n==1||n==2||n==3||n==4)//当输入数据是特殊情况时可直接将结果输出
    {
    printf("1\n");
    continue;
    }
    for(i=599;i>=0&&fib[n][i]==0;i--) ;//消除前面多余的0
 printf("%d",fib[n][i--]);//输出数组存放的前几位(<=4位),这一位要单独输出不能以下面的格式输出,因为这前几位可能还有不需输出的0
    for(;i>=0;i--)
    printf("%04d",fib[n][i]);// %04d 表示在输出一个小于4位的数值时, 将在前面补0使其总宽度为4位,输出格式必须是这样,否则wrong answer
    printf("\n");
    }
    return 0;
}
   

0 0
原创粉丝点击