HDU1575-Tr 【矩阵快速幂】(模板题)

2023-09-11,,

<题目链接>

题目大意:

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 <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm> using namespace std;
const int mod = ; struct Matrix
{
int arr[][];
}init,tmp; int n; Matrix Mul(Matrix a, Matrix b) //矩阵相乘
{
Matrix temp;
for(int i=;i<n;i++)
for (int j = ; j < n; j++)
{
temp.arr[i][j] = ;
for (int k = ; k < n; k++)
{
temp.arr[i][j] = (temp.arr[i][j] + a.arr[i][k] * b.arr[k][j] % mod) % mod;
}
}
return temp;
} Matrix Pow(Matrix ans, Matrix a, int x) //快速
{
while (x)
{
if (x & )
{
ans = Mul(ans, a);
}
x >>= ;
a = Mul(a, a);
}
return ans;
} int main()
{
int t; scanf("%d", &t);
while (t--)
{
int k;
scanf("%d%d", &n, &k);
for (int i = ; i < n; i++)
for (int j = ; j < n; j++)
{
scanf("%d", &init.arr[i][j]);
tmp.arr[i][j] = init.arr[i][j];
}
Matrix ans=Pow(init, tmp, k - ); int res = ;
for (int i = ; i < n; i++)
{
res = (res + ans.arr[i][i]) % mod;
}
printf("%d\n", res);
}
return ;
}

2018-08-08

HDU1575-Tr 【矩阵快速幂】(模板题)的相关教程结束。

《HDU1575-Tr 【矩阵快速幂】(模板题).doc》

下载本文的Word格式文档,以方便收藏与打印。