hdu 1575 Tr A(矩阵乘法快速求幂)

 

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

 

#include <stdio.h> #define size 12 struct node { int map[size][size]; }unit/*单位矩阵*/,init/*初始矩阵*/; int n,m; /*矩阵相乘*/ node Mul(node a,node b) { int i,j,k; node c; for (i=0;i<n;i++) { for (j=0;j<n;j++) { c.map[i][j] = 0; for (k=0;k<n;k++) c.map[i][j]+=a.map[i][k]*b.map[k][j]; c.map[i][j]%=9973; } } return c; } /*二分法矩阵求幂,并求Tr*/ int GetSum() { int i,sum; node c,p,q; p = unit,q = init; while (m!=1) { if (m%2==1) { m--; p = Mul(p,q); } else { m>>=1; q = Mul(q,q); } } c = Mul(p,q); sum = 0; for (i=0;i<n;i++) { sum+=c.map[i][i]; sum%=9973; } return sum; } int main() { int test,i,j; /* freopen("d://1.txt","r",stdin); */ scanf("%d",&test); while (test--) { scanf("%d%d",&n,&m); for (i=0;i<n;i++) { for (j=0;j<n;j++) { scanf("%d",&init.map[i][j]); if(i==j) unit.map[i][j] = 1; else unit.map[i][j] = 0; /*等价于unit.map[i][j] = (i==j)*/ } } printf("%d/n",GetSum()); } return 0; }

你可能感兴趣的:(hdu 1575 Tr A(矩阵乘法快速求幂))