分类 HDU 下的文章

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这个很关键 也就是说它的值怎么着也是0-6 根据这个特性我们发现他这个是会在一个周期内进行循环 问题在于怎么去找这个周期 我们现在先定一个上限值为1000 然后对在循环中如果dp[i-2] == 1 && dp[i-1] == 1 && i != 2 则说明到达了周期 则直接break; 然后回到外面 取n%(i-1) 因为i是到了周期的第一个 所以要-1 返回到周期的末尾

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int a, b, n;
            while (in.hasNext()) {
                a = in.nextInt();
                b = in.nextInt();
                n = in.nextInt();
                if (a == 0 && b == 0 && n == 0) {
                    break;
                }
                int dp[] = new int[1000];
                dp[0] = 1;
                dp[1] = 1;
                int i = 2;
                for (; i < 1000; i++) {
                    dp[i] = (a * dp[i - 1] + b * dp[i - 2]) % 7;
                    if (dp[i - 2] == 1 && dp[i - 1] == 1 && i != 2) {
                        break;
                    }
                }
                out.println(dp[(n - 1) % (i - 2)]);
            }
        }

    }
}