hdu 5950 Recursive sequence 递推式 矩阵快速幂

题目链接

题意

给定\(c_0,c_1,求c_n(c_0,c_1,n\lt 2^{31})\),递推公式为
\[c_i=c_{i-1}+2c_{i-2}+i^4\]

思路

参考

将递推式改写\[\begin{pmatrix}f(n)\\f(n-1)\\n^4\\n^3\\n^2\\n\\1\end{pmatrix}=\begin{pmatrix}1&2&1&4&6&4&1\\1&0&0&0&0&0&0\\0&0&1&4&6&4&1\\0&0&0&1&3&3&1\\0&0&0&0&1&2&1\\0&0&0&0&0&1&1\\0&0&0&0&0&0&1\end{pmatrix}\begin{pmatrix}f(n-1)\\f(n-2)\\(n-1)^4\\(n-1)^3\\(n-1)^2\\(n-1)\\1\end{pmatrix}\]

然后上矩阵快速幂。

// 一开始令\(d_i=c_i-2c_{i-1}\),推出了一个\(d_i=(-1)^{i-2}(d_2-15)+\frac{1}{2}i^4+i^3-\frac{1}{2}i\),虽然接下来也好做但挺烦且容易算错。一上来就应该往矩阵快速幂的方向去想的。

Code

#include <bits/stdc++.h>
#define N 7
using namespace std;
typedef long long LL;
const LL mod = 2147493647;
typedef struct {
    LL mat[N][N];
    void init(LL x){
        memset(mat, 0, sizeof(mat));
        for(int i=0; i<N; i++) mat[i][i] = x;
    }
    void print() const {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) printf("%lld ", mat[i][j]); printf("\n");
        }
    }
} Matrix;
Matrix p = {1,2,1,4,6,4,1,
            1,0,0,0,0,0,0,
            0,0,1,4,6,4,1,
            0,0,0,1,3,3,1,
            0,0,0,0,1,2,1,
            0,0,0,0,0,1,1,
            0,0,0,0,0,0,1
           };
LL add(LL a, LL b) { return (a + b + mod) % mod; }
LL mul(LL a, LL b) { return a * b % mod; }
Matrix mulm(const Matrix& a, const Matrix& b) {
    Matrix temp;
    temp.init(0);
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            for (int k = 0; k < N; ++k) temp.mat[i][j] = add(temp.mat[i][j], mul(a.mat[i][k], b.mat[k][j]));
        }
    }
    return temp;
}
Matrix poww(LL n) {
    Matrix a = p, ret;
    ret.init(1);
    while (n) {
        if (n & 1) ret = mulm(ret, a);
        a = mulm(a, a);
        n >>= 1;
    }
    return ret;
}
void work() {
    LL n, a, b;
    scanf("%lld%lld%lld", &n, &a, &b);
    Matrix m = poww(n-2);
    LL ans = add(add(add(add(add(add(mul(b, m.mat[0][0]), mul(a, m.mat[0][1])), mul(16, m.mat[0][2])),
                  mul(8, m.mat[0][3])), mul(4, m.mat[0][4])), mul(2, m.mat[0][5])), m.mat[0][6]);
    printf("%lld\n", ans);
}
int main() {
    int T;
    scanf("%d", &T);
    while (T--) work();
    return 0;
}


转载于:https://www.cnblogs.com/kkkkahlua/p/7703926.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值