• HDU1005 Number Sequence


    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种可能值了。由该关系式得知每一项只与前两项发生关系,所以当连续的两项在前面出现过循环节出现了,注意循环节并不一定会是开始的 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\n", rec[beg+(n-end)%(end-beg)] );
    31 }
    32 else
    33 printf( "%d\n", rec[n] );
    34 }
    35 return 0;
    36 }

      

  • 相关阅读:
    POJ 1948 Triangular Pastures
    2018ACM/ICPC 青岛现场赛 E题 Plants vs. Zombies
    三大博弈
    ACM-ICPC 2018年北京网络赛 D-80 days
    hdu 2062 Subset sequence
    转-利用 Python 练习数据挖掘
    内联函数
    C++中冒号(:)和双冒号(::)的用法
    理性,感性和爱
    修改IE8搜索框为指定搜索引擎,如CSDN、百度知道等
  • 原文地址:https://www.cnblogs.com/Lyush/p/2165927.html
Copyright © 2020-2023  润新知