Matrix multiplication and its applications

definition

Fast power

  • You can make a function to return the product of two matrices, then using the idea of ​​fast power, you can find the power of a matrix in log time.
  • In fact, except the multiplication part needs to be changed a little, everything else is the same, just pay attention to the initialization.
  • When initializing ksm(), retit needs to be initialized to the identity matrix, that is, a[i][i]=1, and the others are 0 matrices.
  • I wrote a quick power blog post portal before
  • Template title http://blog.csdn.net/jackypigpig/article/details/78453575

application

Quickly find a certain term in the Fibonacci sequence

in conclusion

  • Can make a 2*2 matrix
  • A=[0111]
    <script type="math/tex; mode=display" id="MathJax-Element-2"> A= \begin{bmatrix} 0 & 1\\ 1 & 1 \end{bmatrix} </script>
  • Then you will find that in addition to the first two 1s in the Fibonacci sequence, the nth term is An <script type="math/tex" id="MathJax-Element-3">A^n</script>, you can try it yourself.

prove

  • Can be proved by induction

program

//Luogu-1962
#include <cstdio>
#define Ha 1000000007
typedef long long ll;
struct matrix{ll a[2][2];} A;
ll n;

matrix multi(matrix x,matrix y){
    matrix z={
   
   0};
    for (ll i=0; i<=1; i++)
        for (ll j=0; j<=1; j++)
            for (ll k=0; k<=1; k++)
                z.a[i][j]=(z.a[i][j]+(x.a[i][k]*y.a[k][j])%Ha)%Ha;
    return z;
}

matrix ksm(matrix x,ll y){
    matrix ret={
   
   0};
    ret.a[0][0]=ret.a[1][1]=1;
    for (; y; y>>=1,x=multi(x,x))
        if (y&1) ret=multi(ret,x);
    return ret;
}

int main(){
    A.a[0][0]=0,A.a[0][1]=A.a[1][0]=A.a[1][1]=1;    
    scanf("%lld",&n);
    printf("%lld\n",ksm(A,n-1).a[1][1]) ;
}

Guess you like

Origin blog.csdn.net/jackypigpig/article/details/78363631