UVA 10655 Contemplation! Algebra

题目链接:UVA 10655 Contemplation! Algebra

题目大意:
已知\(a+b\)\(ab\),求\(a^n+b^n\)

题解:
递推式不难推出来。
构造矩阵:

\[\left(\begin{matrix} a^i+b^i \\ a^{i-1}+b^{i-1} \end{matrix}\right) = \left(\begin{matrix} a+b & -ab \\ 1 & 0 \end{matrix}\right) \times \left(\begin{matrix} a^{i-1}+b^{i-1} \\ a^{i-2}+b^{i-2} \end{matrix}\right) \]

所以:

\[\left(\begin{matrix} a^n+b^n \\ a^{n-1}+b^{n-1} \end{matrix}\right) = \left(\begin{matrix} a+b & -ab \\ 1 & 0 \end{matrix}\right)^{n-1} \times \left(\begin{matrix} a+b \\ 2 \end{matrix}\right) \]

另外,题目规定一行只有两个\(0\)时结束,但是存在一行有三个数但前两个是\(0\)的情况,所以不能单纯判断前两个数是不是\(0\)

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define ll long long

struct Matrix {  // 矩阵
    int row, col;
    ll num[2][2];
};

Matrix multiply(Matrix a, Matrix b) {  // 矩阵乘法
    Matrix temp;
    temp.row = a.row, temp.col = b.col;
    memset(temp.num, 0, sizeof(temp.num));
    for (int i = 0; i < a.row; ++i)
        for (int j = 0; j < b.col; ++j)
            for (int k = 0; k < a.col; ++k)
                temp.num[i][j] = (temp.num[i][j] + a.num[i][k] * b.num[k][j]);
    return temp;
}

Matrix MatrixFastPow(Matrix base, ll k) {  // 矩阵快速幂
    Matrix ans;
    ans.row = ans.col = 2;
    ans.num[0][0] = ans.num[1][1] = 1;
    ans.num[0][1] = ans.num[1][0] = 0;
    while (k) {
        if (k & 1) ans = multiply(ans, base);
        base = multiply(base, base);
        k >>= 1;
    }
    return ans;
}

int main() {
    ll p, q, n;
    Matrix base;
    base.row = base.col = 2;
    base.num[1][0] = 1;
    base.num[1][1] = 0;
    while (cin >> p >> q >> n) {
        if (!n) {
            cout << 2 << endl;
            continue;
        }
        base.num[0][0] = p;
        base.num[0][1] = -q;
        Matrix ans = MatrixFastPow(base, n - 1);
        cout << ans.num[0][0] * p + ans.num[0][1] * 2 << endl;
    }
    return 0;
}
posted @ 2021-01-26 20:12  ZZHHOOUU  阅读(79)  评论(0编辑  收藏  举报