矩阵快速幂计算和整数快速幂计算相同。在计算A^7时,7的二进制为111,从而A^7=A^(1+2+4)=A*A^2*A^4.而A^2可以由A*A得到,A^4可以由A^2*A^2得到。计算两个n阶方阵的乘积复杂度为O(n^3)。k的二进制大约有logk位,总的复杂度为O(n^3*logk).
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<queue> #include<iomanip> #include<vector> #include<string.h> #include<algorithm> using namespace std; const int MOD = 9973; class Matrix{ int n; int M[12][12]; Matrix Matrix::operator*(Matrix& X); //矩阵乘法 public: void input(int i, int j, int m){ M[i][j] = m; } Matrix(int n); //初始化 int trSum(); //计算矩阵迹 Matrix quickPower(int k);//矩阵快速幂 }; Matrix::Matrix(int n){ this->n = n; int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) M[i][j] = (i == j ? 1 : 0); } Matrix Matrix::operator*(Matrix& X){ Matrix res(n); int i, j, k, ans; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++){ ans = 0; for (k = 1; k <= n; k++) ans += M[i][k] * X.M[k][j]; res.M[i][j] = ans%MOD; } res.n = n; return res; } int Matrix::trSum(){ int res = 0, i; for (i = 1; i <= n; i++) res += M[i][i]; return res%MOD; } Matrix Matrix::quickPower(int k){ Matrix Y(n); Matrix X = *this; while (k){ if (k & 1) Y = Y*X; k >>= 1; X = X*X; } return Y; } int main(){ int i, j, T, k, n,ans; scanf("%d", &T); while (T--){ scanf("%d%d", &n,&k); Matrix X(n); for (i = 1; i <= n;i++) for (j = 1; j <= n; j++){ scanf("%d", &ans); X.input(i, j, ans); } X = X.quickPower(k); printf("%ld\n",X.trSum()); } return 0; }
时间: 2024-12-18 15:58:40