Last night, the little prince of matrix gave us a brief introduction to the Rapid power of matrix, learned about it, and wrote a template.
1: Thoughts
The idea of the Rapid power of a matrix is the same as that of a fast power of a number. If we want 2 ^ 11 to the power, we can write 11 as 1 + 2 + 8, that is, 2 ^ 0 + 2 ^ 1 + 2 ^ 3. So the time complexity of an O (n) is reduced to log (n)
The idea of the Rapid power of a matrix is exactly the same as that of the Rapid power of the number. That is, you must implement the multiplication of the matrix yourself, and then you can set the template of the Rapid power of the number.
2: Difficulties
The difficulty of a matrix question lies in the construction of a matrix, which is generally used for the question of introducing a recursive formula. After the recursive formula is introduced, it is found that the complexity of recursive O (n) is relatively large, then we can construct a matrix and use the Matrix to quickly reduce the time complexity to log (n) with the power of the matrix.
For example, nyoj 301
This recursive formula is given.
F (x) = A * F (X-2) + B * F (x-1) + C
Then evaluate F (N), n is 10 ^ 9
In this way, the time complexity of direct traversal is definitely not allowed, so we will try to construct a matrix]
| A, 1, 0 | A, 1, 0 | ^ (n-2)
| F (N), F (n-1), 1 | = | f (n-1), F (n-2), 1 | * | B, 0, 0 | = | F2, f1, 1 | * | B, 0, 0 |
| C, 0, 1 | C, 0, 1 |
Then we can directly use the matrix power.
Quick power template:
# Include <cstdio> # include <string> # include <cmath> # include <iostream> using namespace STD; const long M = 1000007; const long n = 3; long long T, B, C, F1, F2; struct node // matrix {long line, Cal; long a [n + 1] [n + 1]; node () {line = 3, Cal = 3; A [0] [0] = B; A [0] [1] = 1; A [0] [2] = 0; A [1] [0] = T; A [1] [1] = 0; A [1] [2] = 0; A [2] [0] = C; A [2] [1] = 0; A [2] [2] = 1 ;}}; node isit (node X, long 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; ans. line = x. line, ans. cal = S. cal; ans = isit (ANS, 0); For (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) % m ;}} return ans ;}long long fast_matrax (long N) // matrix fast power {If (n = 1) return F1; n-= 2; long x = 1, F = N, OK = 1; node ans, TMP, ch; ans. line = 1, ans. cal = 3; ans. A [0] [0] = F2, ans. A [0] [1] = F1, ans. A [0] [2] = 1; while (n> 0) {If (N % 2) {ans = MATLAB (ANS, TMP);} TMP = MATLAB (TMP, TMP); N/= 2;} return ans. A [0] [0];} int main () {long N, T; scanf ("% LLD", & T); While (t --) {scanf ("% LLD", & F1, & F2, & T, & B, & C, & N ); printf ("% LLD \ n", fast_matrax (N) ;}return 0 ;}
Rapid matrix power