Tr A
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
Author
xhd
Source
HDU 2007-1 Programming Contest
矩阵快速幂入门
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxsize 520
#define mod 9973
int n,m;
struct trz
{
int arr[12][12];
};
trz TRZ1, TRZ2;
trz sum(trz a, trz b)
{
trz c;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c.arr[i][j] = 0;
for (int k = 0; k < n; k++)
{
c.arr[i][j] = (c.arr[i][j] + a.arr[i][k] * b.arr[k][j] % mod) % mod;//矩阵乘法
}
c.arr[i][j] %= mod;
}
}
return c;
}
trz pow(trz x,trz y,int a)
{
while (a)//快速幂
{
if (a % 2)
{
y = sum(y,x);//记录临时状态无法被整合的矩阵,并且最后作为乘积的最终答案
}
a /= 2;
x = sum(x, x);//直接矩阵平方
}
return y;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &TRZ1.arr[i][j]);
TRZ2.arr[i][j] = TRZ1.arr[i][j];
}
}
trz ans;
ans = pow(TRZ1, TRZ2,m-1);
int answer = 0;
for (int i = 0; i < n; i++)
{
answer += ans.arr[i][i]%mod;
}
printf("%d\n", answer%mod);
}
system("pause");
return 0;
}