HDU-1005 Number Sequence

10898 ワード

Number Sequence
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 43278    Accepted Submission(s): 9449
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
 
また演算式を与えた数学で、涛神はやはり間違っていない.最適化がなければ、タイムアウトメモリなどは避けられない.この問題は明らかに法則を探す問題であり,すなわちこの問題の解には循環節が存在する.
式f[n]=A*f[n-1]+B*f[n-2];後者は7*7=49種の可能性しかないが,なぜかというと,f[n−1]またはf[n−2]に対する取値は0,1,2,3,4,5,6の7個の数しかなく,A,Bはまた固定されているので49種の可能値しかない.この関係式から,各項は前の2項とのみ関係があることが分かるので,連続する2項が前に過循環節が現れた場合,循環節が必ずしも最初の1,1であるとは限らないことに注意する.また、1組のテストデータのf[n]は49の可能な答えしかないため、最悪の場合、すべての場合に遭遇し、それは50回の演算で循環節を生成する.ループセクションを見つけたら、簡単に解決できます.
コードは次のとおりです.
 1 #include <cstring>
2 #include <cstdio>
3 #include <cstdlib>
4 using namespace std;
5
6 int rec[60];
7
8 int main()
9 {
10 int a, b, n;
11 rec[0] = rec[1] = rec[2] = 1;
12 while( scanf( "%d %d %d", &a, &b, &n ), a | b | n )
13 {
14 int beg, end, flag = 0;
15 for( int i = 3; i <= n && !flag; ++i )
16 {
17 rec[i] = ( a * rec[i-1] + b * rec[i-2] ) % 7;
18 for( int j = 2; j <= i - 1; ++j )
19 {
20 if( rec[i] == rec[j] && rec[i-1] == rec[j-1] )
21 {
22 beg = j, end = i;
23 flag = 1;
24 break;
25 }
26 }
27 }
28 if( flag )
29 {
30 printf( "%d
", rec[beg+(n-end)%(end-beg)] );
31 }
32 else
33 printf( "%d
", rec[n] );
34 }
35 return 0;
36 }