Tr A(矩阵快速幂)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1575

题目:

Problem Description
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
 
 思路:本题要想用矩阵快速幂就得借助单位矩阵(或许是其他方法我没想到吧……),然后就又是一个套模板的题了>_<
 
代码实现如下:
 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 }

猜你喜欢

转载自www.cnblogs.com/Dillonh/p/8972087.html
tr