HDU-1005-Number Sequence (周期)

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 3
1 2 10
0 0 0

Sample Output
2
5

[分析]
一看到式子后面的%7就可以确定会有一个周期了。
但一开始没有想对

一开始的错误想法:周期的开始必定是1和1(dp[1]=1,dp[2]=1),所以一直递推下去,找到两个连续的1就是另一个周期的开始。找到周期长度就容易的到第n个数的值了(dp[n%zhouqi]);

交了一次TLE了,基本上对这个思路就是心如死灰了。但是又想不出更好的。然后就利用这个思路测试各种ab的周期。
然后就发现了TLE的原因………a=123,b=56的时候会出现一种很尴尬的循环1 1 4 2 1 4 2 1 4 2 1………..
然后就一直421回不到11,所以就T了。

那怎么解决呢?又测试了好一会,发现周期都比较短。所以决定在固定长度退出循环,那现在关键就是在什么长度退出了。
于是嵌套了两个for测试最大长度,(上面的那种尴尬循环要跳过,不然测不出来)。发现固定最大周期是48,一发AC。

[代码]

#include<iostream>
#include<string>
#include<cstdio>
#include<map>
using namespace std;
int dp[6388600];
int main()
{

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


/* 1 1
1 1 2 3 5 1 6 0 6 6 5 4 2 6 1 0 1 1
*/

猜你喜欢

转载自blog.csdn.net/q435201823/article/details/79995388