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<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int mod=9973;
struct node
{
ll ma[101][101];
};
int n,k;
node mul(node a,node b)
{
node ans;
memset(ans.ma,0,sizeof ans.ma);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++)
ans.ma[i][j]=(ans.ma[i][j]+a.ma[i][k]*b.ma[k][j])%mod;
return ans;
}
node pow(node a,int b)
{
node ans;
memset(ans.ma,0,sizeof ans.ma);
for(int i=1;i<=n;i++) ans.ma[i][i]=1;
while(b)
{
if(b&1) ans=mul(ans,a);
a=mul(a,a);
b>>=1;
}
return ans;
}
int main()
{
int t;
cin >>t;
while(t--)
{
scanf("%d %d",&n,&k);
node a;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&a.ma[i][j]);
node ans=pow(a,k);
ll sum=0;
for(int i=1;i<=n;i++) sum=(sum+ans.ma[i][i])%mod;
cout <<sum<<endl;
}
return 0;
}