Tr A (矩阵快速幂)

该博客介绍了如何使用矩阵快速幂算法来计算一个方阵的迹的幂次模9973,提供了输入输出示例,并给出了题解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A为一个方阵,则Tr A表示A的迹(就是主对角线上各项的和),现要求Tr(A^k)%9973。
Input
数据的第一行是一个T,表示有T组数据。
每组数据的第一行有n(2 <= n <= 10)和k(2 <= k < 10^9)两个数据。接下来有n行,每行有n个数据,每个数据的范围是[0,9],表示方阵A的内容。
Output
对应每组数据,输出Tr(A^k)%9973。
Sample Input
2
2 2
1 0
0 1
3 99999999
1 2 3
4 5 6
7 8 9
Sample Output
2
2686
题解:

#include<iostream>
#include<cstring>
using namespace std;
const int mod=9973;
const int maxn=15;
struct Matrix{
    long long mat[maxn][maxn];
};
Matrix unit;  //单位矩阵
int n;
Matrix mul(Matrix a,Matrix b){
    Matrix c;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++){
            c.mat[i][j]=0;
            for(int k=0;k<n;k++){
                c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                c.mat[i][j]%=mod;
            }
    }
    return c;
}
Matrix mat_pow(Matrix a,long long b){
    Matrix temp=unit;
    while(b){
        if(b%2)
            temp=mul(temp,a);
        a=mul(a,a);
        b/=2;
    }
    return temp;
}
int main(){
    memset(unit.mat,0,sizeof(unit.mat));
    for(int i=0;i<maxn;i++)
        unit.mat[i][i]=1;
    int t;
    cin>>t;
    while(t--){
        long long k;
        cin>>n>>k;
        Matrix a;
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
                cin>>a.mat[i][j];
        Matrix b=mat_pow(a,k);
        long long result=0;
        for(int i=0;i<n;i++)
            result=(result+b.mat[i][i])%mod;
        cout<<result<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值