hdu 1575 Tr A

Tr A

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4203    Accepted Submission(s): 3142


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
 
Author
xhd
 
Source
 
Recommend
linle   |   We have carefully selected several similar problems for you:  1588 2256 2604 2254 3117 
 
典型的矩阵快速幂,根据矩阵快速幂的模板,很容易写出来。
 
题意:求一个矩阵的k次方后的对角线上的和取膜。
 
附上代码:
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #define mod 9973
 5 using namespace std;
 6 struct mat
 7 {
 8     int m[10][10];
 9 };
10 int n;
11 mat mul(mat a,mat b)
12 {
13     mat c;
14     int i,j,k;
15     memset(c.m,0,sizeof(c.m));
16     for(i=0; i<n; i++)
17         for(j=0; j<n; j++)
18         {
19             for(k=0; k<n; k++)
20                 c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
21             c.m[i][j]%=mod;
22         }
23     return c;
24 }
25 
26 mat product(mat a,int k)
27 {
28     if(k==1) return a;
29     else if(k&1)
30         return mul(product(a,k-1),a);
31     else
32         return product(mul(a,a),k/2);
33 }
34 
35 int main()
36 {
37     int T,i,j,k;
38     mat a,b;
39     scanf("%d",&T);
40     while(T--)
41     {
42         scanf("%d%d",&n,&k);
43         for(i=0; i<n; i++)
44             for(j=0; j<n; j++)
45                 scanf("%d",&a.m[i][j]);
46         b=product(a,k);
47         int ans=0;
48         for(i=0; i<n; i++)
49             ans=(ans+b.m[i][i])%mod;
50         printf("%d
",ans);
51     }
52     return 0;
53 }
原文地址:https://www.cnblogs.com/pshw/p/5545931.html