UVA10689 Yet another Number Sequence【数列+矩阵快速幂】

Let’s define another number sequence, given by the following function:

f(0) = a

f(1) = b

f(n) = f(n − 1) + f(n − 2), n > 1

  When a = 0 and b = 1, this sequence gives the Fibonacci Sequence. Changing the values of a and b, you can get many different sequences. Given the values of a, b, you have to find the last m digits of f(n).

Input

The first line gives the number of test cases, which is less than 10001. Each test case consists of a single line containing the integers a b n m. The values of a and b range in [0, 100], value of n ranges in [0, 1000000000] and value of m ranges in [1, 4].

Output

For each test case, print the last m digits of f(n). However, you should NOT print any leading zero.

Sample Input

4

0 1 11 3

0 1 42 4

0 1 22 4

0 1 21 4

Sample Output

89

4296

7711

946

问题链接UVA10689 Yet another Number Sequence

问题简述:(略)

问题分析

  一个典型的数列计算问题,一般用矩阵快速幂来解。该题的解法类似于斐波那契数列的矩阵快速幂解法。

程序说明:(略)

题记:(略)

参考链接:(略)

AC的C++语言程序如下:

/* UVA10689 Yet another Number Sequence */

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 2;
int MOD;

struct Matrix
{
    LL m[N][N];

    Matrix()
    {
        memset(m, 0, sizeof(m));
    }

    // 矩阵相乘
    Matrix operator * (const Matrix& y)
    {
        Matrix z;

        for(int i=0; i<N; i++)
            for(int j=0; j<N; j++)
                for(int k=0; k<N; k++) {
                    z.m[i][j] += m[i][k] * y.m[k][j] % MOD;
                    z.m[i][j] %= MOD;
                }

        return z;
    }
};

// 矩阵快速幂
Matrix Matrix_Powmul(Matrix x, int m)
{
    Matrix z;
    z.m[0][1] = z.m[1][0] = 0;
    z.m[0][0] = z.m[1][1] = 1;

    while(m) {
        if(m & 1)
            z = z * x;
        x = x * x;
        m >>= 1;
    }

    return z;
}

int main()
{
    int t;
    cin >> t;
    while(t--) {
        int a, b, n, m;

        cin >> a >> b >> n >> m;

        MOD = 1;
        while(m--)
            MOD *= 10;

        Matrix x;
        x.m[0][0] = x.m[0][1] = x.m[1][0] = 1;
        x.m[1][1] = 0;
        Matrix t = Matrix_Powmul(x, n);

        printf("%lld\n", (b * t.m[1][0] + a * t.m[1][1]) % MOD);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/81382880