hdu1005 Number Sequence

来源:互联网 发布:刷屏软件下载 编辑:程序博客网 时间:2024/05/08 04:37

Number Sequence

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


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 31 2 100 0 0
 

Sample Output
25



一般给出运算公式的,如果没有优化的话,超时超内存等等是避免不了的了。所以要找规律,前面两个等于1,
如果有两个连着的1出现,那就是出现循环周期了。(因为每一个f[n]只与前两个有关),找到循环节就是解决这个问题的关键。 
由于计算f[n]时要mod 7, 所以f[n]的值只有 0,1,2,3,4,5,6 这7个数; 又A,B又是固定的,所以对于(A * f[n-1] + B * f[n-2]),
只有7 * 7 = 49 种可能值。 
所以最坏的情况下,会在第50次运算中出现循环节,即f[51]=f[1],f[52]=f[2]......
(笔者这里循环变量i是从3开始的,第50次运算时i=52) 

#include<cstdio>int main(){int a,b,n,i,s[53];while(scanf("%d%d%d",&a,&b,&n),a||b||n) {s[1]=1;s[2]=1;for(i=3;i<53;i++){s[i]=(a*s[i-1]+b*s[i-2])%7;if(s[i]==1&&s[i-1]==1)break;//如果出现循环节,则终止循环 }n=n%(i-2);//如果n%(i-2)=0,则s[n]=s[i-2]; s[0]=s[i-2];//直接令s[0]=s[i-2], 当n%(i-2)=0,可直接输出s[n] printf("%d\n",s[n]);}return 0;} 





0 0