Matrix multiplication is an efficient algorithm that can optimize some one-dimensional recursion to log (n), and can also find path scheme, so it is an application-strong algorithm. Matrix, is one of the basic concepts in linear algebra. A matrix of MXN is a number array in which the number of MXN is ranked as m rows n columns. Because it puts a lot of data together in a compact way, it's sometimes easy to represent complex models. Matrix multiplication looks strange, but it is actually very useful and widely used.
Basic Definition
It is defined so that axB is meaningful only if the number of columns of matrix a is equal to the number of rows in matrix B . A matrix of mxn (m,n) left multiplied by an nxp b ( n,p), a matrix C(m,p) of mxp is obtained Meet
Matrix multiplication satisfies the binding rate but does not meet the exchange rate
The general moment multiplication must combine the fast power to have the effect "
http://poj.org/problem?id=3070
#include <cstdio>#include<iostream>using namespacestd;Const intMOD =10000;structmatrix{intm[2][2];} ans,BaseMatrix Mul (matrix A, matrix B) {matrix tmp; for(intI=0; i<2; ++i) { for(intj=0; j<2; ++j) {Tmp.m[i][j]=0; for(intk=0; k<2; ++k) Tmp.m[i][j]= (Tmp.m[i][j]+a.m[i][k]*b.m[k][j])%MOD; } } returntmp;}intFast_mod (intN) { Base. m[0][0] =Base. m[0][1] =Base. m[1][0] =1; Base. m[1][1] =0; ans.m[0][0] = ans.m[1][1] =1; ans.m[0][1] = ans.m[1][0] =0; while(n) {if(n&1) {ans= Mul (ans,Base); } Base= Mul (Base,Base); N>>=1; } returnans.m[0][1];}intMain () {intN; while(SCANF ("%d", &n) &&n!=-1) {printf ("%d\n", Fast_mod (n)); } return 0;}
View Code
Slightly optimized:
#include <cstdio>#include<cstring>#include<iostream>using namespacestd;Const intMOD =10000;structmatrix{intm[2][2];} ans,BaseMatrix Mul (matrix A, matrix B) {matrix tmp; memset (tmp.m,0,sizeof(tmp.m)); for(intI=0; i<2; i++) for(intk=0; k<2; k++) if(A.m[i][k]) for(intj=0; j<2; J + +) Tmp.m[i][j]= (Tmp.m[i][j]+a.m[i][k]*b.m[k][j])%MOD; returntmp;}intFast_mod (intN) { Base. m[0][0] =Base. m[0][1] =Base. m[1][0] =1; Base. m[1][1] =0; ans.m[0][0] = ans.m[1][1] =1; ans.m[0][1] = ans.m[1][0] =0; while(n) {if(n&1) {ans= Mul (ans,Base); } Base= Mul (Base,Base); N>>=1; } returnans.m[0][1];}intMain () {intN; while(SCANF ("%d", &n) &&n!=-1) {printf ("%d\n", Fast_mod (n)); } return 0;}
View Code
Matrix Fast Power