HDU ACM 1005 Number Sequence

Number Sequence

 

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 119732    Accepted Submission(s): 29072

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
 
Author
CHEN, Shunbao
 
Source
 
c++程序代码
 1 #include <stdio.h>
 2 #include <iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     int i,a,b,n;
 7     char f[1000];
 8     while(scanf("%d%d%d",&a ,&b ,&n)!=EOF)
 9     {
10         if(a == 0 && b==0 && n == 0) return 0;
11         f[0] = 1 ; f[1] = 1;
12         if(n == 1 || n == 2){
13             printf("1\n");
14             continue;
15         }
16         
17         for(i = 2 ;i < 1000 ; i++)
18         {
19             f[i]=(a*f[i-1]+b*f[i-2])%7;
20             if(f[i-2] == 1 && f[i-1] == 1 && i != 2) break;
21         }
22         printf("%d\n",f[(n-1)%(i-2)]);
23     }
24     return 0;
25 }

解题报告:作为一个初级编程者,看到这样的题目的时候最简单的想法就是使用递归方法解决。实际上,作为练习,递归就可以了。但是递归方法每次计算值的时候时间复杂度很大,达到2^(n/2)<T(n)<2^(n)(致谢http://bbs.pediy.com/showthread.php?t=123051),并且随着n的增大而呈级数级增大。所以必须用更有效的方法去解决。

因为对于f(n)来说,当n>=2时候,f(n)只可能为0-6之间的数字。f[i]=(a*f[i-1]+b*f[i-2])%7,如果能够在f(n)中能够找到他的循环周期的话,那么只要用f[(n-1)/T]]即可在数组f中找到其对应的值,其算法复杂度仅仅只有O(i),这个i远远小于n。当这个n值越大,这种周期式的算法优势就越明显。

 

//注释:因为无论是多么优秀的算法,只要当 a、b、n中的n足够大时候,都不行,除非找到他的规律,
//         这样的话,计算一个周期T内f(n)的值即可解决问题。剩余的只要输出f[(n-1)/T]就行了。

 

致谢:谢谢HDU ACM 提供题目,谢谢http://www.cnblogs.com/kuangbin/archive/2011/07/26/2117381.html的帮助。

posted @ 2015-04-04 18:30  ACMFresh  阅读(2052)  评论(0编辑  收藏  举报