Optimization Matrix Linear Recursive acceleration

First look at the definition:

 

can not read it? So with the idea of ​​cycling to explain;

First you have to know that only the number of rows and columns of a matrix phase while the second matrix multiplication makes sense.

Then, the answer to the elements C (i, j) on, and can be understood as a product ~ on i-th row j-th column of A and B;

Therefore, when the matrix during acceleration, can be calculated by enumerating i, j, k;

Here the famous Fibonacci deed that the number of columns to achieve the code:

#include <bits/stdc++.h>
#define p 1000000007
using namespace std;
long long st[10][10];
long long tmp[10][10];
long long a[10][10];
void cheng1()
{
    memset(tmp,0,sizeof(tmp));
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            tmp[1][i]+=(st[1][j]*a[j][i])%p;
            tmp[i][j]%p;
        }
    }
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            st[i][j]=tmp[i][j];
        }
    }
}
void cheng2()
{
    memset(tmp,0,sizeof(tmp));
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            for(int k=1;k<=2;k++){
                tmp[i][j]+=(a[k][j]*a[i][k])%p;
                tmp[i][j]%=p;
            }
        }
    }
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            a[i][j]=tmp[i][j];
        }
    }
}
void JZKSM(long long n)
{
    while(n){
        if(n&1) cheng1();
        cheng2();
        n/=2;
    }
}
int main()
{
    long long n;
    cin>>n;
    a[1][1]=1,a[1][2]=1,a[2][1]=1;
    st[1][1]=1,st[1][2]=1;
    JZKSM(n-2);
    if(n==1||n==2){
        cout<<"1";
        return 0;
    }
    cout<<st[1][1]%p;
}

 

Guess you like

Origin www.cnblogs.com/kamimxr/p/11498317.html