杭电ACM step2.2.6Number Sequence

本文探讨了一道数列求值的编程题,通过逐步优化,从超时到内存溢出,最终找到有效的解决方案。文章详细记录了使用暴力求解、动态规划以及利用数列周期性的过程。

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

这道题虽然不是很难(看着好像不难),代码量也不大,但是我经历了超时,超内存才整出来,所以把这题记录下来

Problem Description

A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).

Input

The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.

Output

For each test case, print the value of f(n) on a single line.

Sample Input

1 1 3
1 2 10
0 0 0

Sample Output

2
5

Time Limit Exceeded

#include<cstdio>

int main()
{
	int A,B,n;
	while(scanf("%d%d%d",&A,&B,&n)!=EOF)
	{
		if(A==0&&B==0&&n==0)
			break;
		int fn_1=1,fn_2=1;
		int fn_3;
		for(int i=2;i<n;i++)
		{
			fn_3=(A*fn_2+B*fn_1)%7;
			fn_1=fn_2;
			fn_2=fn_3;
		}
		
		printf("%d\n",fn_3);
		
	}
	return 0;
}

代码思路是简单,就暴力求解……n的数据很大,就会超时

Memory Limit Exceeded

#include<cstdio>
#include<vector>
using namespace std;

int main()
{
	int A,B,n;
	while(scanf("%d%d%d",&A,&B,&n)!=EOF)
	{
		if(A==0&&B==0&&n==0)
			break;
		
		vector<int> m;
		int fn_1=1,fn_2=1;
		int fn_3;
		m.push_back(fn_1);m.push_back(fn_2);
		for(int i=2;i<n;i++)
		{
			fn_3=(A*fn_2+B*fn_1)%7;
			fn_1=fn_2;
			fn_2=fn_3;
			if(fn_2==1&&fn_1==1)
			{
				break;
			}
			else
				m.push_back(fn_2);
		}
		if(n==1||n==2)
			printf("1\n");
		else
			printf("%d\n",m[(n-1)%(m.size()-1)]);
	}
	return 0;
}

用vector来解,空间不够……这个的思路就是求循环的一个周期,跟着计算就可

AC代码

#include<cstdio>
int main()
{
	int A,B,n;
	while(scanf("%d%d%d",&A,&B,&n)!=EOF)
	{
		int m[49];
		if(A==0&&B==0&&n==0)
			break;
		int fn_1=1,fn_2=1;
		int fn_3;
		m[0]=1;m[1]=1;
		for(int i=2;i<49;i++)
		{
			fn_3=(A*fn_2+B*fn_1)%7;
			fn_1=fn_2;
			fn_2=fn_3;
			m[i]=fn_2;
		}
		
		printf("%d\n",m[(n-1)%49]);
		
	}
	return 0;
}

f(n-1)与f(n-2)的取值范围为[0,6],七种情况,49(7*7)是一个循环(也可能比49小)
只记录49之前的就可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值