【模板】矩阵快速幂

#include<cstdio>
#include<cstring>

using namespace std;

typedef long long LL;

const int N = 105;
const LL MOD = 1e9 + 7;
LL n, x;

struct Matrix{
    LL ma[N][N];
    void init(LL h, LL l){
        for(int i = 1; i <= h; i++){
            for(int j = 1; j <= l; j++){
                if(i ^ j)   ma[i][j] = 0;
                else    ma[i][j] = 1;
            }
        }
    }
    void init(){
        memset(ma, 0, sizeof ma);
    }
}A;

Matrix mul(Matrix a, LL an, LL am, Matrix b, LL bn, LL bm){
    Matrix res;
    res.init();
    if(am ^ bn){
        puts("Invalid!");
        return res;
    }
    for(int i = 1; i <= an; i++)
        for(int j = 1; j <= bm; j++)
            for(int k = 1; k <= am; k++)
                (res.ma[i][j] += a.ma[i][k] * b.ma[k][j] % MOD) %= MOD;
    return res;
}

Matrix f_pow(Matrix bs, LL len, LL idx){
    Matrix res;
    res.init(len, len);
    for(int i = 1; i <= len; i++)
        for(int j = 1; j <= len; j++)
            bs.ma[i][j] %= MOD;
    while(idx){
        if(idx & 1) res = mul(res, n, n, bs, n, n);
        bs = mul(bs, n, n, bs, n, n);
        idx >>= 1;
    }
    return res;
}

int main(){
    scanf("%lld%lld", &n, &x);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            scanf("%lld", &A.ma[i][j]);
    Matrix ans = f_pow(A, n, x);
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++)
            printf("%lld ", ans.ma[i][j]);
        putchar(10);
    }
    return 0;
}

0 条评论

目前还没有评论...