杭电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).
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
25求解历程:乍一看以为这只是简单的考查递归,然而用这种方法提交的结果是STACK OVERFLOW(栈溢出),显然是n过大时栈空间不够,不符要求。不用递归那也只能用循环迭代了,第二次我申请了一个容量为100,000,000的数组,然后用循环将n个数赋值,结果是Memory Limit Exceeded(超内存)。第三次我只用了三个临时变量来存f(n),f(n-1),f(n-2),但时间复杂度是O(n),结果是Time Limit Exceeded(超时)。最后在网上搜索其解,发现是利用其结果是具有循环性的,具体解释如下:f(n)是对7求模的结果,只有0,1,2,3,4,5,6这7种情况,而f(n)是由前两个数确定的,所以只要有相邻的两个数与前面的相邻的两个数相等就出现了循环。两个数共有7*7=49种情况,所以49个数内必有一个循环。利用循环求解的时间复杂度将大大降低,成功的C++代码如下:
#include<iostream> using namespace std; int main(){ int A, B, n; cin >> A >> B >> n; while (A||B||n) { int f[100] = {0}; f[1] = f[2] = 1; for (int i=3; i <= 99; i++) f[i]= (A*f[i-1] + B*f[i-2]) % 7; int begin=1; //循环开始的位置 int end = 2; //循环结束的后一个位置 bool judge=0; for (int j = 1; j < 99; j++){ for (int i = j + 1; i < 99; i++){ if (f[i] == f[j] && f[i + 1] == f[j + 1]){ begin = j; end = i; judge = 1; break; } } if (judge) break; } if (n <= begin) cout << f[n] << endl; else if ((n - begin + 1) % (end - begin) != 0) cout << f[(n - begin + 1) % (end - begin) + begin - 1] << endl; else cout << f[end - 1] << endl; cin >> A >> B >> n; } return 0; }