Description
If a is a square matrix, tr a indicates the trace of A (the sum of all items on the primary diagonal). tr (a ^ K) % 9973 is required.
Input
The first row of data is a T, indicating that there is a T group of data.
The first row of each data group contains N (2 <= n <= 10) and K (2 <= k <10 ^ 9) data. Next there are n rows, each row has n data, and the range of each data is [], which indicates the content of square matrix.
Output
Output tr (a ^ K) % 9973 for each group of data.
Sample Input
22 21 00 13 999999991 2 34 5 67 8 9
Sample output
22686
Idea: Just a matrix multiplication quick power
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MOD = 9973;struct Matrix {int arr[12][12];}init, unit;int n,k;Matrix Mul(Matrix a, Matrix b) {Matrix c;for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {c.arr[i][j] = 0;for (int k = 0; k < n; k++)c.arr[i][j] = (c.arr[i][j]+(a.arr[i][k]*b.arr[k][j])%MOD)%MOD;}return c;}Matrix Pow(Matrix a, Matrix b, int x) {while (x) {if (x & 1)b = Mul(b, a);x >>= 1;a = Mul(a, a);}return b;}int main() {int t;scanf("%d", &t);while (t--) {scanf("%d%d", &n, &k);for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {scanf("%d", &init.arr[i][j]);unit.arr[i][j] = init.arr[i][j];}Matrix res = Pow(init, unit, k-1);int ans = 0;for (int i = 0; i < n; i++) ans = (ans + res.arr[i][i]) % MOD;printf("%d\n", ans%MOD);}return 0;}