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

查看:87
本文介绍了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;
}

解决方案

以下討論都限定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

这篇关于c++ - 如何理解OJ答案中的这段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆