• HDU 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).
    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
    看了这个数据,n的值有点大,第一反应就是矩阵快速幂,不过AC之后才感觉不用那么复杂,不过还是矩阵快速幂做比较放心
    #include <iostream>
    #include <cstdio>
    using namespace std;
    struct Mat
    {
        int matrix[2][2];
    };
    Mat Multi(const Mat& a, const Mat& b)
    {
    int i, j, k;
    Mat c;
    for (i = 0; i < 2; i++)
    {
       for (j = 0; j < 2; j++)
       {
        c.matrix[i][j] = 0;
        for (k = 0;k < 2; k++)
         c.matrix[i][j] += a.matrix[i][k] * b.matrix[k][j] % 7;
        c.matrix[i][j] %= 7;
       }
    }
    return c;
    }int main()
    {
        int A, B, n;
        int f[3];
        while(scanf("%d%d%d",&A,&B,&n)!=EOF && !(A==0 && B==0 && n==0))
        {
            Mat stand = {0, 1, B, A};
            Mat e = {1, 0, 0, 1};
            f[1]=1;f[2]=1;
             if (n <= 2)
             {
                  printf("%d
    ", f[n]);
                  continue;
             }
             Mat ans = e;
             Mat tmp = stand;
             n = n - 2;
             while(n)
             {
                if (n & 1)
                ans = Multi(ans, tmp);
                tmp = Multi(tmp, tmp);
                n >>= 1;
             }
             printf("%d
    ", (ans.matrix[1][0] * f[1] + ans.matrix[1][1] * f[2]) % 7);
         }
    return 0;
    }
    至少做到我努力了
  • 相关阅读:
    函数高阶(函数,改变函数this指向,高阶函数,闭包,递归)
    案例:新增数组方法
    案例:商品查询
    案例:forEach和some区别
    ES5新增方法(数组,字符串,对象)
    案例:借用父构造函数继承属性和方法
    构造函数 和 原型
    汽车小常识别让六大汽车驾驶软肋阻碍你
    Opencv 图像增强和亮度调整<6>
    C# StringBulider用法<1>
  • 原文地址:https://www.cnblogs.com/chensunrise/p/3686141.html
Copyright © 2020-2023  润新知