hdoj1005 Number Sequence(找規律)

來源:http://acm.hdu.edu.cn/showproblem.php?pid=1005

很明顯找規律的題目,因爲它給出的n太大,遍歷的話一定會超時。

代碼如下:

#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
int t[90000001];
int main()
{
	int a,b,n,i,cycle,j;
	while(~scanf("%d%d%d",&a,&b,&n))
	{
		if(a==0&&b==0&&n==0)break;
		t[1]=1;t[2]=1;cycle=0; 
		for(i=3;i<=n;i++)
		{
			t[i]=(t[i-1]*a+t[i-2]*b)%7;
			for(j=2;j<i;j++)
			{
				if(t[j]==t[i]&&t[j-1]==t[i-1])
				{
					cycle=i-j;break;
				}
			}
			if(cycle>0)break;
		}
		if(cycle>0)
		t[n]=t[(n-j)%cycle+j];
		printf("%d\n",t[n]);
	   
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章