Tr A (matrix fast power)

Topic link: http://acm.hdu.edu.cn/showproblem.php?pid=1575

topic:

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.
 

 

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
 
 Idea: In order to use the matrix fast power in this question, you have to use the unit matrix (maybe I didn't think of other methods...), and then it is another template question >_<
 
The code is implemented as follows:
 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int mod = 9973;
 5 int t, n, k;
 6 int a[15][15], T[15][15];
 7 
 8 void mul(int a[15][15], int b[15][15]) {
 9     int c[15][15];
10     memset(c, 0, sizeof(c));
11     for(int i = 0; i < n; i++) {
12         for(int j = 0; j < n; j++) {
13             for(int k = 0; k < n; k++) {
14                 c[i][j] = (c[i][j] + (long long)a[i][k] * b[k][j] % mod) % mod;
15             }
16         }
17     }
18     memcpy(a, c, sizeof(c));
19 }
20 
21 
22 int main() {
23     scanf("%d", &t);
24     while(t--) {
25         scanf("%d%d", &n, &k);
26         memset(T, 0, sizeof(T));
27         for(int i = 0; i < n; i++) {
28             T[i][i] = 1;
29             for(int j = 0; j < n; j++) {
30                 scanf("%d", &a[i][j]);
31             }
32         }
33         for(; k; k >>= 1) {
34             if(k & 1) mul(T, a);
35             mul(a, a);
36         }
37         long long ans = 0;
38         for(int i = 0; i < n; i++) {
39             ans = (ans + T[i][i]) % mod;
40         }
41         printf("%lld\n", ans % mod);
42     }
43     return 0;
44 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325085765&siteId=291194637