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