HDOJ1005-Number-Sequence

56次阅读

共计 817 个字符,预计需要花费 3 分钟才能阅读完成。

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 取模这个特点. 测试数据感觉不太严谨,这个做法只能通过 HDOJ 的测试数据,但是很明显有些数据这种做法是 ac 不了的。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
    int A,B,n;

    while(cin >> A >> B >>n){if(0 == A && 0 == B && 0 == n){return 0;}
        vector<int> result(48);
        result[1] = 1;
        result[2] = 1;
        for(int i = 3; i <= 48; i++){result[i] =(A * result[i-1] + B * result[i-2]) % 7;
        }
        cout << result[n%48] << endl;
    }
    return 0;
}

最后 ac。

正文完
 0