递推+矩阵快速幂

1 篇文章 0 订阅

题目描述
由于长度为一的方块只有一种方案,长度为二的有四种方案(不包含长度为一中的情况),长度为三的有两种方案(不包含长度为二中的情况),得递推式:
f[i] = f[i-1] + f[i-2] * 4 + f[i-3] * 2;
由于n <= 10 ^ 18, 考虑使用矩阵快速幂,用如下矩阵存状态:
f[i], 0, 0
f[i+1], 0, 0
f[i+2], 0, 0
用如下矩阵转移状态:
0, 1, 0
0, 0, 1
2, 4, 1
代码:

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>

#define For(i,j,k) for(LL i = j;i <= k;i ++)
const int Mod = 1000000007;
typedef long long LL;

struct Matrix{
    const static int N = 3;
    LL M[N][N];

    Matrix(int c = 0){
        memset(M, 0, sizeof(M));
        if(c == 1)
            For(i,0,N-1)
                M[i][i] = 1;
        if(c == 2){
            M[0][1] = M[1][2] = M[2][2] = 1;
            M[2][0] = 2, M[2][1] = 4;
        }
        if(c == 3){
            M[0][0] = M[1][0] = 1;
            M[2][0] = 5;
        }
    }

    Matrix operator * (const Matrix &B) const{
        Matrix C;
        For(i,0,N-1)
            For(j,0,N-1)
                For(k,0,N-1)
                    C.M[i][j] = (C.M[i][j] + M[i][k] * B.M[k][j]) % Mod;
        return C;
    }

    Matrix operator ^ (LL exp) const{
        Matrix Ans(1), T = *this;
        while(exp){
            if(exp & 1) Ans = Ans * T;
            T = T * T;
            exp >>= 1;
        }
        return Ans;
    }

    void print() const{
        For(i,0,N-1)
            For(j,0,N-1)
                printf("%lld%c", M[i][j], j == N - 1 ? '\n' : ' ');
    }

};

LL n;
int main(){
    scanf("%lld", &n);
    Matrix Ans = (Matrix(2) ^ n) * 3;
    printf("%lld\n", Ans.M[0][0]);
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值