HDU1005 Number Sequence 题解 矩阵快速幂

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1005

题目大意:
已知:f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7
现在告诉你 A,B,n,求 f(n)

解题思路:
矩阵快速幂。

\[\begin{bmatrix} f(n)\\ f(n-1) \end{bmatrix} = \begin{bmatrix} A & B \\ 1 & 0 \end{bmatrix}^{n-2} \begin{bmatrix} f(2)\\ f(1) \end{bmatrix} \]

实现代码如下(略丑):

#include <bits/stdc++.h>
using namespace std;
struct Matrix {
    int a[2][2];
    Matrix() {
        memset(a, 0, sizeof(a));
    }
};
Matrix multi(Matrix a, Matrix b) {
    Matrix c;
    for (int i = 0; i < 2; i ++)
        for (int j = 0; j < 2; j ++)
            for (int k = 0; k < 2; k ++)
                c.a[i][k] = (c.a[i][k] + a.a[i][j]*b.a[j][k])%7;
    return c;
}
int A, B, n;
Matrix f(int n) {
    Matrix a;
    a.a[0][0] = A; a.a[0][1] = B;
    a.a[1][0] = 1; a.a[1][1] = 0;
    if (n == 1) return a;
    Matrix b = f(n/2);
    b = multi(b, b);
    if (n%2) b = multi(b, a);
    return b;
}
int main() {
    while (~scanf("%d%d%d", &A, &B, &n) && A) {
        int ans;
        if (n <= 2) ans = 1;
        else {
            Matrix mm = f(n-2);
            ans = (mm.a[0][0] + mm.a[0][1]) % 7;
        }
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2020-01-13 23:27  quanjun  阅读(93)  评论(0编辑  收藏  举报