最惊心动魄的矩阵一章~~~
Tr A |
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) |
Total Submission(s): 51 Accepted Submission(s): 45 |
|
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 <cstdlib> 3 #include <iostream> 4 #include <cstring> 5 #include <string> 6 #include <algorithm> 7 using namespace std; 8 9 const int maxn=13; 10 const int mod=9973; 11 struct matrix 12 { 13 int m[maxn][maxn]; 14 }; 15 matrix a,b,base,ans,c; 16 int n,k,sum,T; 17 18 void close() 19 { 20 exit(0); 21 } 22 23 matrix mul(matrix a,matrix b) 24 { 25 memset(c.m,0,sizeof(c.m)); 26 for (int i=1;i<=n;i++) 27 for (int j=1;j<=n;j++) 28 for (int k=1;k<=n;k++) 29 { 30 c.m[i][j]+=a.m[i][k]*b.m[k][j]; 31 c.m[i][j] %= mod; 32 } 33 return c; 34 } 35 36 void print(matrix a) 37 { 38 for (int i=1;i<=n;i++) 39 { 40 for (int j=1;j<=n;j++) 41 printf("%d ",a.m[i][j]); 42 printf("\n"); 43 } 44 } 45 46 void work() 47 { 48 //ans -> 答案 base->乘方 49 base=a; 50 for (int i=1;i<=n;i++) 51 for (int j=1;j<=n;j++) 52 if (i==j) 53 ans.m[i][i]=1; 54 else 55 ans.m[i][j]=0; 56 while (k!=0) 57 { 58 if (k & 1) 59 { 60 ans=mul(base,ans); 61 } 62 k/=2; 63 base=mul(base,base); 64 } 65 } 66 67 void init() 68 { 69 while (scanf("%d",&T)!=EOF) 70 { 71 while (T--) 72 { 73 while (scanf("%d %d",&n,&k)!=EOF) 74 { 75 for (int i=1;i<=n;i++) 76 for (int j=1;j<=n;j++) 77 scanf("%d",&a.m[i][j]); 78 work(); 79 sum=0; 80 for (int i=1;i<=n;i++) 81 sum=(sum+ans.m[i][i]) % mod; 82 printf("%d\n",sum); 83 } 84 } 85 } 86 } 87 88 int main () 89 { 90 init(); 91 close(); 92 return 0; 93 }