hdu 1250 Hat's Fibonacci

本文介绍了一种使用高精度累加处理大数问题的方法,并提供了两种不同的实现方案。一种采用字符串操作来实现2005位数的计算,另一种则利用int64类型进行更高效的存储和计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大数题,高精度累加。

分析一:用字符串操作,要达到2005位;估计第8000项的样子能达到;时间复杂度为O(8000*2000)--》》》O(10^8)

分析二:用int八位八位的存,所以二位数组的第二位只要开到255就够了;时间复杂度为0(8000*255)——》0(10^6)

我下面的代码用int64写的,为了更省时;

代码一:

#include<iostream>
#include<string>
using namespace std;
char ch[8000][2010];

int main()
{

	int n;
	while(scanf("%d", &n) != EOF)
	{
		memset(ch, '0', sizeof(ch));
		ch[1][0] = '1';
		ch[2][0] = '1';
		ch[3][0] = '1';
		ch[4][0] = '1';
		int i, j, t, p = 0;
		for(i = 5; i <= n; i++)
		{
			for(j = 0; j <= p; j++)
			{
				t = ch[i-1][j] + ch[i-2][j] + ch[i-3][j] + ch[i-4][j] - 4 * '0';
				ch[i][j+1] += t / 10;
				if(ch[i][j] + t % 10 >= 10 + '0')
				{
					ch[i][j+1]++;
					ch[i][j] += t % 10 - 10;
				}
				else
					ch[i][j] += t % 10;
			}
			if(ch[i][j] == '0')
				p = j - 1;
			else
				p = j;
		}
		for(j = p; j >= 0; j--)
			printf("%c", ch[n][j]);
		printf("\n");
	}
	return 0;
}
代码二:
#include<iostream>
#define M 8000
#define N 165
using namespace std;

__int64 ch[M][N];


void cal()
{
	memset(ch, 0, sizeof(ch));
	ch[1][1] = ch[2][1] = ch[3][1] = ch[4][1] = 1;
	int i, j;
	__int64 t;
	for(i = 5; i < M; i++)
	{
		t = 0;
		for(j = 1; j < N; j++)
		{
			t += ch[i-1][j] + ch[i-2][j] + ch[i-3][j] + ch[i-4][j];
			ch[i][j] = t % 10000000000000000;
			t /= 10000000000000000;
		}
	}
}

int main()
{
	int n, i;
	cal();
	while(scanf("%d", &n) != EOF)
	{
		i = N-1;
		while(ch[n][i] == 0)
			i--;
		printf("%I64d", ch[n][i--]);
		while(i)
			printf("%016I64d", ch[n][i--]);//%016Id表示不足16位的前面补0
		printf("\n");
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值