Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4965
Give you a n * k matrix A and a k * n matrix B (4 <= n <= 1000) and (2 <= k <= 6 ), then, perform the following four steps:
- Calculate a new matrix C = a * B
- Calculate M = C ^ (N * n)
- For each element % 6 in m
- Add each element in m to calculate the sum.
That is, find a * B *...... * A * B but a * B forms a matrix of N * n, and the N size may be 1000. Therefore, the time complexity is very high. Even a fast power cannot pass. Now there is a conversion: a * B * *...... * B * a * B is now converted into a K * k matrix, and K is at most 6, saving time complexity, pay attention to the calculation of POW (B * a, n * N-1), to the result left by a A, right by a B, you can get the answer. I did not answer this question at the end (the time was not reasonably allocated, and the question was stuck = ).......
# Include <cstdio> # include <cstring> # include <iostream> # include <algorithm> using namespace STD; const int maxn = 1017; # define M 6 struct matrix {int V [6] [6] ;}; int n, m, K; // matrix size int A [maxn] [6], B [6] [maxn], C [maxn] [6], d [maxn] [maxn]; Matrix T, E; matrix mtmul (matrix A, matrix B) // evaluate the matrix A * B {int I, j, k; matrix C; for (I = 0; I <m; I ++) for (j = 0; j <m; j ++) {C. V [I] [J] = 0; For (k = 0; k <m; k ++) C. V [I] [J] = (. V [I] [k] * B. V [k] [J] + C. V [I] [J]) % m;} return C;} matrix mtpow (matrix origin, int K) // matrix fast power {int I; matrix res; memset (res. v, 0, sizeof (res. v); for (I = 0; I <m; I ++) res. V [I] [I] = 1; while (k) {If (K & 1) RES = mtmul (Res, origin); origin = mtmul (origin, origin ); k> = 1;} return res;} void out (matrix A) {for (INT I = 0; I <m; I ++) {for (Int J = 0; j <m; j ++) cout <. V [I] [J] <"; cout <Endl;} void ini T () {memset (T. v, 0, sizeof (T. v); memset (C, 0, sizeof (c); memset (D, 0, sizeof (d);} int main () {While (~ Scanf ("% d", & N, & M) {If (n = 0 & M = 0) break; Init (); for (INT I = 0; I <n; I ++) // the size of matrix A N * m {for (Int J = 0; j <m; j ++) {scanf ("% d", & A [I] [J]) ;}}for (INT I = 0; I <m; I ++) // size of matrix B M * n {for (Int J = 0; j <n; j ++) {scanf ("% d ", & B [I] [J]) ;}}for (INT I = 0; I <m; I ++) // The size of Matrix T = B * A is M * m {for (Int J = 0; j <m; j ++) {for (int K = 0; k <n; k ++) {T. V [I] [J] + = B [I] [k] * A [k] [J]; T. V [I] [J] % = m; }}// out (t); E = mtpow (t, n * N-1); For (INT I = 0; I <n; I ++) // matrix C = A * E is N * m {for (Int J = 0; j <m; j ++) {for (int K = 0; k <m; k ++) {C [I] [J] + = A [I] [k] * E. V [k] [J]; C [I] [J] % = m ;}} int ans = 0; For (INT I = 0; I <N; I ++) // matrix D = C * B size is N * n {for (Int J = 0; j <n; j ++) {for (int K = 0; k <m; k ++) {d [I] [J] + = C [I] [k] * B [k] [J];} ans + = d [I] [J] % m;} printf ("% d \ n", ANS);} return 0 ;}