Usually used to accelerate recurrence.
Simply,. There are columns for fib. F0 = 1. F1 = 1,FN = fn-1 + fn-2 (n >= 2).
Then for fN there are:
In general. FOR fn = a1*f (n-1) + a2*f (n-2) + .... +a (n-1) *f1, there are:
Because the matrix multiplication satisfies the binding law, the a^n can be obtained by the high-speed power to achieve the recursive effect.
By the way, a little trick:
Taking POJ 3233 as an example
#include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include < cstdio> #include <queue> #include <cmath> #include <stack> #include <map> #pragma comment ( linker, "/stack:1024000000"); #define EPS (1e-8) #define LL long long#define ULL unsigned long long#define _ll __int64#defin E INF 0x3f3f3f3fusing namespace std;int mod;const int maxn = 61;struct mat{LL MAT[MAXN][MAXN]; int r,c; void Init (int val,int r,int c) {R = R,c = C; for (int i = 1;i <= R, ++i) for (int j = 1;j <= C; ++j) if (i! = j) Mat[i] [j] = 0; else mat[i][j] = val; }}; Mat Matrixmult (Mat A,mat b) {mat p; P.init (0,A.R,B.C); for (int i = 1;i <= A.R, ++i) {for (int j = 1;j <= B.C, ++j) {for (int k = 1;k <= b.r; ++K) {P.mat[i][j] + = a.mat[i][k]*b.mat[k][j]; p.mat[i][J]%= Mod; }}} return p;} Mat Quickmult (_ll K,mat Coe) {mat p; P.init (1,COE.R,COE.C); while (k >= 1) {if (k&1) p = matrixmult (P,coe); Coe = Matrixmult (Coe,coe); K >>= 1; } return p;} int main () {_ll n,k,m; int i,j; Mat A, B; scanf ("%lld%lld%lld", &n,&k,&m); Mod = m; for (i = 1;i <= n; ++i) {for (j = 1;j <= n; ++j) scanf ("%lld", &a.mat[i][j]); } for (i = 1;i <= N, ++i) {for (j = 1;j <= N; ++j) {if (i = = j) a.mat[i ][j+n] = 1; else a.mat[i][j+n] = 0; }} for (i = 1;i <= N, ++i) {for (j = 1;j <= N; ++j) {a.mat[i+n][j] = 0; }} for (i = 1;i <= N, ++i) {for (j = 1;j <= N; ++j) {if (i = = j) A. Mat[i+n][j+n] = 1; else a.mat[i+n][j+n] = 0; }} A.R = 2*N,A.C = 2*n; A = Quickmult (k+1,a); for (i = 1;i <= n; ++i) {if (a.mat[i][i+n]) a.mat[i][i+n]--; else a.mat[i][i+n] = m-1; } for (i = 1;i <= n; ++i) {for (j = 1;j <= N; ++j) {printf ("%lld", A.mat[i][j+n]); if (j = = N) printf ("\ n"); else printf (""); }} return 0;}
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Started his high-speed power matrix.