Tr A
Problem Description
A is a square matrix, then Tr A represents the trace of A (that is, the sum of the items on the main diagonal), and now Tr(A^k)%9973 is required.
Input
The first row of data is a T, indicating that there are T groups of data.
The first row of each set of data has two data, n (2 <= n <= 10) and k (2 <= k < 10^9). Next there are n lines, each line has n data, each data range is [0,9], representing the content of the square matrix A.
The first row of each set of data has two data, n (2 <= n <= 10) and k (2 <= k < 10^9). Next there are n lines, each line has n data, each data range is [0,9], representing the content of the square matrix A.
Output
Corresponding to each set of data, 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
Matrix fast exponentiation template to find the main diagonal sum after
Ak .
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef vector<int> vec; 4 typedef vector<vec> mat; 5 const int mod = 9973; 6 mat mul(mat &A, mat &B) { 7 mat C(A.size(), vec(B[0].size())); 8 for(int i = 0; i < A.size(); i ++) { 9 for(int j = 0; j < B[0].size(); j ++) { 10 for(int k = 0; k < B.size(); k ++) { 11 C[i][j] = (C[i][j] + A[i][k]*B[k][j])%mod; 12 } 13 } 14 } 15 return C; 16 } 17 18 mat pow(mat A, int n) { 19 mat B(A.size(), vec(A.size())); 20 for(int i = 0; i < A.size(); i ++) B[i][i] = 1; 21 while(n) { 22 if(n&1) B = mul(B,A); 23 A = mul(A,A); 24 n >>= 1; 25 } 26 return B; 27 } 28 int main() { 29 int t, n, k; 30 cin >> t; 31 while(t--) { 32 cin >> n >> k; 33 mat A(n, vec(n)); 34 for(int i = 0; i < n; i ++) { 35 for(int j = 0; j < n; j ++) { 36 cin >> A[i][j]; 37 } 38 } 39 mat B = pow(A, k); 40 int ans = 0; 41 for(int i = 0; i < n; i ++) { 42 ans = (ans+B[i][i])%mod; 43 } 44 cout << ans << endl; 45 } 46 return 0; 47 }