您的位置:首页 > 其它

HDUoj 1575 Tr A ( 矩阵快速幂

2017-08-16 21:54 323 查看

Tr A

Description

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


题解:

裸的不能再裸的矩阵快速幂TAT

AC代码

#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int mod = 9973;
int n;
struct node {
int arr[20][20];
};
node mul(node x, node y)
{
node ans;
memset(ans.arr,0,sizeof(ans.arr));
for(int i = 0;i < n; i++) {
for(int j = 0;j < n; j++) {
for(int k = 0;k < n; k++) {
ans.arr[i][j] = (ans.arr[i][j]+x.arr[i][k]*y.arr[k][j]%mod)%mod;
}
}
}
return ans;
}
node powMod(int u, node x)
{
node ans;
for(int i = 0;i < n; i++) {
for(int j = 0;j < n; j++) {
ans.arr[i][j] = x.arr[i][j];
}
}
while(u) {
if(u&1) ans = mul(ans,x);
x = mul(x,x);
u>>=1;
}
return ans;
}
int main()
{
int T;
cin>>T;
while(T--) {
int m;
node x;
scanf("%d%d",&n,&m);
for(int i = 0;i < n; i++) {
for(int j  = 0; j < n; j++) {
scanf("%lld",&x.arr[i][j]);
}
}
x = powMod(m-1,x);
int sum = 0;
for(int i = 0; i < n; i++) sum = (sum+x.arr[i][i])%mod;
printf("%d\n",sum%mod);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: