1005 Number Sequence(周期规律)

题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1005

Memory Limit Exceeded(内存超限)的代码 :
错误示范,用的递归但是超时了。

#include <bits/stdc++.h>
using namespace std;
int A,B,n;
const int maxn = 1e8;
int a[maxn];
void fn(){
	a[1] = a[2] = 1;
	for(int i =3;i<=maxn;i++){
		a[i] = (A * a[i-1] + B * a[i-2])% 7;
	}
}
int main(){
	ios::sync_with_stdio(0);
	while(cin>>A>>B>>n&&A!=0&&B!=0&&n!=0){
	    fn();
	    cout<<a[n]<<endl;
	    memset(a,0,sizeof(a));
	} 
	return 0;
} 

AC代码:
发现for循环小于等于1000时会Time Limit Exceeded,但是只小于时就AC掉???
由于f(n)会mod7,所以猜测可能存在周期性,

if(a[i]==1&&a[i-1]==1)  break

判读如果存在那么就结束计算每个值,然后利用周期性来输出答案即可。可以理解为是在找规律。

#include <bits/stdc++.h>
using namespace std;
int A,B,n,i,T;
int a[1000];
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	a[1] = a[2] = 1;
	while(cin>>A>>B>>n && ( A!=0 || B!=0  || n!=0)){
	    for(i = 3;i<1000;i++){
	    	a[i] = ( A * a[i-1] + B * a[i-2]) % 7;
	    	if(a[i]==1&&a[i-1]==1){//完成一个周期 
	    		break;
			}
		}
		T = i-2;//周期的值 
		if(n%T==0) cout<<a[T]<<endl;
		else{
			cout<<a[n%T]<<endl;
		}
	} 
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值