Given an n-order matrix A, calculate the value of the main diagonal of the K-power matrix of A and the value of the modulus 9973.
Solution: the rapid power of a matrix. Can I write a matrix class and then write a few corresponding functions, such as overloading *, so that it is very convenient to directly calculate it like an integer.
Code:
[Cpp]
// Define a matrix class and then reload * to calculate the rapid power of the matrix (the modulo operation during multiplication and addition does not affect the result)
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <string>
# Include <queue>
Using namespace std;
Const long MAXN = 15;
Class Matrix {
Public:
Long m [MAXN] [MAXN];
Matrix (){}
// Initialization
Void init (long num [MAXN] [MAXN]) {
For (int I = 0; I <MAXN; I ++ ){
For (int j = 0; j <MAXN; j ++ ){
M [I] [j] = num [I] [j];
}
}
}
// Sum function
Long Sum (Matrix & M ){
Long sum = 0;
For (int I = 0; I <MAXN; I ++ ){
For (int j = 0; j <MAXN; j ++ ){
If (I = j)
Sum + = M. m [I] [j] % 9973; // remember to modulo each step.
Sum % = 9973;
}
}
Return sum;
}
// Multiplication of overloaded Matrices
Friend Matrix operator * (Matrix & m1, Matrix & m2 ){
Int I, j, k;
Matrix temp;
For (I = 0; I <MAXN; I ++ ){
For (j = 0; j <MAXN; j ++ ){
Temp. m [I] [j] = 0;
For (k = 0; k <MAXN; k ++)
Temp. m [I] [j] + = (m1.m [I] [k] * m2.m [k] [j]) % 9973;
Temp. m [I] [j] % = 9973;
}
}
Return temp;
}
// Rapid power of the matrix
Friend Matrix quickpow (Matrix & M, long n ){
Matrix tempans; // The Rapid power of the tempans Matrix must be the unit Matrix.
// Tempans Initialization
For (int I = 0; I <MAXN; I ++ ){
For (int j = 0; j <MAXN; j ++ ){
If (I = j)
Tempans. m [I] [j] = 1;
Else
Tempans. m [I] [j] = 0;
}
}
// Rapid power of the matrix
While (n ){
If (n & 1)
Tempans = tempans * M;
N = n> 1;
M = M * M;
}
Return ans;
}
};
Int main (){
Matrix A, ans;
Long T, n, k, sum; // the data type is long.
Long num [MAXN] [MAXN]; // input data is stored in the num Array
Scanf ("% lld", & T );
While (T --){
Scanf ("% lld \ n", & n, & k );
Memset (num, 0, sizeof (num ));
For (int I = 0; I <n; I ++ ){
For (int j = 0; j <n; j ++)
Scanf ("% lld", & num [I] [j]);
}
A. init (num); // initialize A Matrix
Ans = quickpow (A, k); // obtain the rapid power of the matrix
Sum = ans. Sum (ans); // obtain the sum of the primary diagonal
Printf ("% d \ n", sum );
}
}
Author: cgl1079743846