Luogu P1939 【模板】矩阵加速(数列)

gate

矩阵乘法加速模板qwq

感觉比之前写的好看了点

代码如下

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
#define int long long
using namespace std;

const int mod = 1e9+7;
int t,n;

struct matrix {
    int ma[3][3];
    matrix() {
        memset(ma,0,sizeof(ma));
    }
} a,b;

matrix operator * (const matrix &A,const matrix &B) {
    matrix C;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            for(int k = 0; k < 3; k++)
                C.ma[i][j] = (C.ma[i][j] + (A.ma[i][k] * B.ma[k][j])%mod )%mod;
    return C;
}

matrix qpow(matrix a,int b) {
    matrix ans,base = a;
    for(int i = 0; i < 3; i++)
        ans.ma[i][i] = 1;
    while(b) {
        if(b&1) ans = ans * base;
        base = base * base;
        b >>= 1;
    }
    return ans;
}

main() {
    scanf("%lld",&t);
    a.ma[0][1] = a.ma[1][2] = a.ma[2][0] = a.ma[2][2] = 1;
    b.ma[0][0] = b.ma[1][0] = b.ma[2][0] = 1;
    while(t--) {
        scanf("%lld",&n);
        if(n <= 3) printf("1
");
        else printf("%lld
",(qpow(a,n-3)*b).ma[2][0]%mod);
    }
}
原文地址:https://www.cnblogs.com/mogeko/p/11824099.html