HDU - 1575——矩阵快速幂问题

时间:2023-03-09 04:57:22
HDU - 1575——矩阵快速幂问题

HDU - 1575

题目:

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
其实,矩阵快速幂问题,和整数快速幂问题是差不多,模板基本相同。
可以自己去对比以下,我博客有关与整数快速幂的随笔。
本题的代码实现如下:
import java.util.Scanner;

class Matrix
{
int m[][] = new int[11][11];
}
public class Main
{
static Scanner cin = new Scanner(System.in);
static final int RE = 9973;
public static void main(String []agrs)
{
int T = cin.nextInt();
for(int i = 0; i < T; i++)
{
int n = cin.nextInt();
int k = cin.nextInt();
QuickPower(n,k);
}
}
static void QuickPower(int n,int k)
{
Matrix k1,ans;
k1 = new Matrix();
ans = new Matrix();
for(int i = 0; i < n; i++)//双重循环是得出单位矩阵
{
for(int j = 0; j < n; j++)
{
k1.m[i][j] = cin.nextInt();
if(i == j)
{
ans.m[i][j] = 1;
}
else
{
ans.m[i][j] = 0;
}
}
}
while(k != 0)
{
if((k & 1) != 0)
{
ans = Mul(ans,k1,n);
}
k1 = Mul(k1,k1,n);
k = k>>1;
}
int sum = 0;
for(int i = 0; i < n; i++)
{
sum = (sum + ans.m[i][i])%RE;
}
System.out.println(sum);
}
static Matrix Mul(Matrix a,Matrix b,int n)
{
Matrix result = new Matrix();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
result.m[i][j] = 0;
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
for(int k = 0; k < n; k++)
{
result.m[i][j] = (result.m[i][j] + a.m[i][k]*b.m[k][j])%RE;
}
}
}
return result;
}
}