杭电ACM 1005 Number Sequence
</p>
Number Sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 38553 Accepted Submission(s): 8150
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
2 5
刚拿到这个题时,想用递归从后往前推(但是感觉好复杂),但是似乎从f(3)循环一直计算到f(n),但是超出了时间限制;
因此,应该是用到了周期性的思想;
解题思路:
1)从式子出发,发现是对7取余,因此初步推算f(n)最多有七种不同的情况
2)再者当A,B确定时,f(n-1),f(n-2)最多有7*7种不同的组合
3)因此根据鸽巢原理,当列举的组合超过49种时,必定会有重复的组合,因此该数列具有周期性,找出周期
算法步骤:
1)循环输入A、B、n,
2)对于每种情况的A、B、n,算前50种组合(确保可以出现重复组合),即算到f(52)为止
3)对于每种组合,查找之前是否有相同的组合,判断条件为:f(i)==f(j)&&f(i-1)==f(j-1)
如果找到了相同的组合,计算其周期,以及周期规律开始的位置,切记要跳出循环
4)最后计算f(n)并输出
以上步骤针对如下代码,因此代码中不做赘述了
#include<iostream> using namespace std; int main() { int A,B,n; while(cin>>A>>B>>n&&(A+B+n)) { long s[52]; int T,t; s[1]=1;s[2]=1; for(int i=3;i<=52;i++) { s[i]=(A*s[i-1]+B*s[i-2])%7; for(int j=2;j<=i-1;j++) { if(s[i]==s[j]&&s[i-1]==s[j-1]) { T=i-j; t=j; break; } } } if(n<t)cout<<s[n]<<endl; else cout<<s[(n-t)%T+t]<<endl; } }