Construct a Matrix to solve the problem [nyoj299 Matrix Power Series], nyoj299matrix
Another new usage of the matrix is to construct the matrix for a rapid power.
For example, nyoj299 Matrix Power Series
Given A recursive formula: S = A +2 +3 +... + Ak.
Let you calculate s. A is A matrix, and k is very large. What should we do?
Inference discovery: Fn = A + A * F (n-1)
Then we can construct the matrix:
(Fn, 1) = (Fn-1, 1) * (A, 0. A, 1) = (F1, 1) * (A, 0. A, 1) ^ K-1
Then we can use a matrix to quickly power it.
The following is the template question code:
# Include <cstdio> # include <string> # include <cmath> # include <iostream> using namespace std; int M; const long N = 32*2; long t, b, c, f1, f2; struct tree // basic matrix {long line, cal; long a [N + 1] [N + 1] ;}; struct Node // constructor matrix {long line, cal; long a [N + 1] [N + 1]; Node (tree x) {line = x. line * 2; cal = 2 * x. cal; for (int I = 0; I <x. line * 2; I ++) {for (int j = 0; j <x. cal; j ++) {a [I] [j] = x. a [I % x. line] [j] ;}} fo R (int I = 0; I <x. line; I ++) for (int j = x. cal; j <x. cal * 2; j ++) a [I] [j] = 0; for (int I = x. line; I <2 * x. line; I ++) {for (int j = x. cal; j <2 * x. cal; j ++) {if (I = j) a [I] [j] = 1; else a [I] [j] = 0 ;}}}}; node isit (Node x, long c) // matrix initialization {for (long I = 0; I <N; I ++) for (long j = 0; j <N; j ++) x. a [I] [j] = c; return x;} Node Matlab (Node x, Node s) // matrix multiplication {Node ans (x); ans. line = x. line, ans. cal = s. cal; ans = isit (ans, 0); for (long Long I = 0; I <x. line; I ++) {for (long j = 0; j <x. cal; j ++) {for (long k = 0; k <s. cal; k ++) {ans. a [I] [j] + = x. a [I] [k] * s. a [k] [j]; ans. a [I] [j] = (ans. a [I] [j]) % M ;}} return ans;} Node Fast_Matrax (tree x, long n) // matrix fast power {Node ans (x ), tmp (x); for (int I = 0; I <ans. line/2; I ++) // chushihua {for (int j = 0; j <ans. cal; j ++) {ans. a [I] [j] = ans. a [I + ans. line/2] [j]; // printf ("% d", ans. a [I] [j]) ;}} ans. line/= 2; while (N> 0) {if (n % 2) {ans = Matlab (ans, tmp);} tmp = Matlab (tmp, tmp); n/= 2 ;} return ans;} int main () {int n, k, m; while (~ Scanf ("% d", & n, & k, & m) {M = m; tree p; p. line = n, p. cal = n; for (int I = 0; I <n; I ++) for (int j = 0; j <n; j ++) scanf ("% d", & p. a [I] [j]); Node ans = Fast_Matrax (p, k-1); for (int I = 0; I <ans. line; I ++) {for (int j = 0; j <ans. cal/2; j ++) printf ("% d", ans. a [I] [j]); puts ("") ;}} return 0 ;}