UVa 10655 Contemplation! Algebra 矩阵快速幂

利用矩阵快速幂求解特定数列
本文介绍了一种使用矩阵快速幂方法求解形如(a^n + b^n)的问题,其中已知(a + b)和(ab)。通过构造特定矩阵并运用快速幂技巧,可以高效地解决该类问题。
题意:

给出\(p=a+b\)\(q=ab\),求\(a^n+b^n\)

分析:

这种题目关键还是在于构造矩阵:
\(\begin{bmatrix} 0 & 1 \\ -(a+b) & ab \end{bmatrix} \begin{bmatrix} a^{n-1}+b^{n-1}\\ a^n+b^n \end{bmatrix} = \begin{bmatrix} a^n+b^n\\ a^{n+1}+b^{n+1} \end{bmatrix}\)

注意不要遇到\(p,q\)都为\(0\)时就退出,因为测试数据中是有这种情况的。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long LL;

struct Matrix
{
    LL a[2][2];

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

    Matrix operator * (const Matrix& t) const {
        Matrix ans;
        for(int i = 0; i < 2; i++)
            for(int j = 0; j < 2; j++)
                for(int k = 0; k < 2; k++)
                    ans.a[i][j] += a[i][k] * t.a[k][j];
        return ans;
    }
};

Matrix Pow(Matrix a, LL p) {
    Matrix ans;
    ans.a[0][0] = ans.a[1][1] = 1;
    while(p) {
        if(p & 1) ans = ans * a;
        a = a * a;
        p >>= 1;
    }
    return ans;
}

LL p, q, n;

int main()
{
    while(scanf("%lld%lld", &p, &q) == 2) {
        if(p == 0 && q == 0) break;
        scanf("%lld", &n);
        if(n == 0) { printf("2\n"); continue; }
        Matrix M;
        M.a[0][1] = 1;
        M.a[1][0] = -q;
        M.a[1][1] = p;
        M = Pow(M, n - 1);
        LL ans = M.a[1][0] * 2 + M.a[1][1] * p;
        printf("%lld\n", ans);
    }

    return 0;
}

转载于:https://www.cnblogs.com/AOQNRMGYXLMV/p/5260379.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值