Hdu1575Tr A矩阵
矩阵快速幂,就是快速幂的乘法变成矩阵乘法,其余的都一样。
#include <cstdio> #include <algorithm> #include <iostream> #include <string.h> using namespace std; const int mod = 9973; const int maxn = 12; struct Matrix { int m[maxn][maxn]; }; int n; Matrix Mul(Matrix a, Matrix b) { Matrix ans; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ ans.m[i][j] = 0; for (int k = 0; k < n; k++){ ans.m[i][j] += (a.m[i][k] * b.m[k][j]); ans.m[i][j] %= mod; } } } return ans; } Matrix fast(Matrix a, int sum) { Matrix ans; for (int i = 0; i < n;i++) for (int j = 0; j < n; j++) ans.m[i][j] = (i == j); while (sum){ if (sum & 1) ans = Mul(ans, a); a = Mul(a, a); sum /= 2; } return ans; } int main() { int t,k; cin >> t; Matrix a; while (t--){ cin >> n >> k; for (int i = 0; i < n;i++) for (int j = 0; j < n; j++) cin >> a.m[i][j]; Matrix gao = fast(a, k); int ans = 0; for (int i = 0; i < n; i++) ans += gao.m[i][i], ans %= mod; printf("%d\n", ans); } return 0; }