【HDU 1005】 Number Sequence

来源:互联网 发布:java时间戳转换成秒 编辑:程序博客网 时间:2024/06/06 02:54

Number Sequence

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


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
 

分析:显然是一道递推的题目,但是注意n最大为1亿,直接递推会超时。

又发现每一个元素都是对七取余的,并且公式是恒定的,则必有循环节在其中。

所以我们只需要寻找循环的长度,最后取模即可。

代码:

#include<iostream>#include<cstdio>using namespace std;int a[100000005],n,A,B;int main(){    a[1]=1,a[2]=1;    while (scanf("%d%d%d",&A,&B,&n) && A+B+n)    {        int k,s=0;        for (int i=3;i<=n;++i)        {            a[i]=(A*a[i-1]+B*a[i-2])%7;            for (k=2;k<i;++k)                if (a[i-1]==a[k-1] && a[i]==a[k])                {                    s=i-k;                    break;                }            if (s>0) break;        }        if (s>0) a[n]=a[(n-k)%s+k];        printf("%d\n",a[n]);    }    return 0;}


原创粉丝点击