矩阵快速幂 裸 hdu1575

裸题,求A^n次后的对角线数字之和

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<string.h>
 4 using namespace std;
 5 const int mod=9973;
 6 int n,m;
 7 struct node
 8 {
 9     int a[15][15];
10 }ans,base;
11 node mat(node x,node y)
12 {
13     node c;
14     for(int i=0;i<n;i++)
15     for(int j=0;j<n;j++){
16         c.a[i][j]=0;
17     }
18     for(int i=0;i<n;i++)
19     for(int j=0;j<n;j++)
20     for(int k=0;k<n;k++){
21         c.a[i][j]=(c.a[i][j]+x.a[i][k]*y.a[k][j]%mod)%mod;
22     }
23     return c;
24 }
25 node quick_mod()
26 {
27     node tmp;
28     for(int i=0;i<=n;i++)
29     for(int j=0;j<=n;j++){
30         if(i==j) tmp.a[i][j]=1;
31         else tmp.a[i][j]=0;
32     }
33     while(m){
34         if(m&1) tmp=mat(tmp,base);
35         base=mat(base,base);
36         m>>=1;
37     }
38     return tmp;
39 }
40 int main()
41 {
42     int T;
43     scanf("%d",&T);
44     while(T--){
45         scanf("%d%d",&n,&m);
46         for(int i=0;i<n;i++)
47         for(int j=0;j<n;j++){
48             scanf("%d",&base.a[i][j]);
49         }
50         ans=quick_mod();
51         int tmp=0;
52         for(int i=0;i<n;i++)
53             tmp=(tmp+ans.a[i][i])%mod;
54         printf("%d\n",tmp);
55     }
56     return 0;
57 }

猜你喜欢

转载自www.cnblogs.com/pangbi/p/11503892.html