递推+矩阵快速幂


由于长度为一的方块只有一种方案,长度为二的有四种方案(不包含长度为一中的情况),长度为三的有两种方案(不包含长度为二中的情况),得递推式:
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 
#include 
#include 
#include 
#include 

#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;
}

你可能感兴趣的:(DP,矩阵)