HDU 1005.Number Sequence【用递归会超时】(2.5)

来源:互联网 发布:sqlserver history 编辑:程序博客网 时间:2024/05/17 00:10

又到周五,假期完全没有星期几的概念。。。

Number Sequence

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


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

总结:

         起初读题,以为会用递归做(开始方了,因为递归学的不好T_T)但是从n的范围看来,很明显,这题不能直接按公式用递归来求,因为n最大可以达到100,000,000,会栈溢出。所以要找规律:取模就是周期性最好的标志。即当前两个等于1,所以后面如果有两个连着的1出现,那就是出现周期了。表示成代码为: if(f[i]==1&&f[i-1]==1),从而i-2就是这个函数的周期啦~这个题比较简单,但是很有代表性哦~尤其是取模与周期性(可以直接看出周期T)关系。

代码如下:

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int a,b,n,f[11000];
    f[1]=1;
    f[2]=1;
    while(scanf("%d%d%d",&a,&b,&n)!=EOF)
    {
        int i;
        if(a==0&&b==0&&n==0)
            break;
        for(i=3;i<11000;i++)
        {
            f[i]=(a*f[i-1]+b*f[i-2])%7;
            if(f[i]==1&&f[i-1]==1)
                break;
        }
        f[0]=f[i-2];
        printf("%d\n",f[n%(i-2)]);
    }
    return 0;
}


0 0