hdu1250 Hat's Fibonacci 斐波那契数列与大数加法

Hat's Fibonacci

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12254    Accepted Submission(s): 4105


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.
 

Author
戴帽子的

思路:将每次大数加法计算结果存储到滚动数组里面最后输出n对应的结果即可。

Code:
#include 
using namespace std;
const int AX = 3e3;
const int mod = 1e4;
int a[5][AX];
int main(){
	int n;
	while( ~scanf("%d",&n) ){
		if( n <= 4 ) {
			cout << "1" << endl;
			continue;
		}
		memset( a, 0 ,sizeof(a) );
		a[0][0] = a[1][0] = a[2][0] = a[3][0] = 1;
		int cur = 3 , len = 0;

		for( int i = 4 ; i < n ; i ++ ){
			cur = ( cur == 4 ? 0 : cur + 1 );
			memset( a + cur , 0 , AX );
			for( int k = 1 ; k < 5 ; k ++ ){
				int tmp = ( cur + k >= 5 ? cur + k - 5 : cur + k ); 
				for( int j = 0 ; a[tmp][j] ; j ++ ){
					a[cur][j] += a[tmp][j];
					if( a[cur][j] > mod ){
						len = max( len , j + 1 );
						a[cur][j+1] += a[cur][j] / mod;
						a[cur][j] %= mod;
					}
				}
			}
		}

		cout << a[cur][len];
		for( int i = len - 1 ; i >= 0 ; i-- ){
			printf("%04d",a[cur][i]);
		}
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(大数)