首页 >社区问答列表 >c++ - 如何理解OJ答案中的这段代码?

c++ - 如何理解OJ答案中的这段代码?

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

#include <iostream>
using namespace std;
int f[54] = {0, 1, 1};
int main()
{
    int A, B, n, q = 1;
    while (cin >> A >> B >> n && A && B && n)
    {
        for (int i = 3; i < 54; ++i)
        {
            f[i] = (A * f[i - 1] + B * f[i - 2]) % 7;   //这里
            if (i > 4)
            {    if (f[i - 1] == f[3] && f[i] == f[4])
                {
                    q = i - 4; //特别是这个地方

                }
            }
        }
        cout << f[n % q] << endl;  //这里

    }

    return 0;
}

  • 给我你的怀抱
  • 给我你的怀抱    2017-06-24 09:44:592楼

    网上不是有解题报告么。这题找规律啊,这题的 q 就是在找周期 T 啊。至于为什么只找前54个,这需要数学严格的推理吧。我测试了下,53也行,52以下不可以。

    --------------题外话-------------

    这种题的话,一眼看过去就是 打表 或者 找规律。

    在这题不是错题的前提下,这种题肯定无外乎两种解法:暴力打表 或 找规律 ,前者说明此题就是个大水题,后者说明这题是推理题,是不是水,看推理的难度,但就本题而言,大水题,看下网上的解题报告就知道了,有人直接把数组开到1000,直到找到周期,跳出。

    +0添加回复

  • 回复
  • 曾经蜡笔没有小新
  • 曾经蜡笔没有小新    2017-06-24 09:44:591楼

    以下討論都限定i>=1:

    • 顯然f(i) \in { 0 .. 6}

    • 所以<f(i-2), f(i-1)>這個狀態空間是有限的, 最大不超過49

    • 所以f(i)是有週期的, 且49是一個週期

    • 然後枚舉出這個週期的全體, 找到和f(n)處於週期中相同位置的那個數

    補充:

    • 你代碼中q不是最短週期, 其實可以在找到第一個週期時停下

    • 當n是49的倍數時一定返回f[0]=0 這可能是個bug

    +0添加回复

  • 回复