P1939 [Template] Matrix acceleration (sequence)

Title: Matrix acceleration

Ideas: You can read this blog, which has a conclusion https://www.cnblogs.com/Mrsrz/p/7629374.html

Code:

#include <set>
#include <map>
#include <queue>
#include <stack>
#include <math.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define zero(a) fabs(a)<eps
#define max( x, y )  ( ((x) > (y)) ? (x) : (y) )
#define min( x, y )  ( ((x) < (y)) ? (x) :(y) )
#define lowbit(x) (x&(-x))
#define debug(a) cerr<<#a<<"=="<<a<<endl
typedef long long LL;
const double pi=acos(-1.0);
const double eps=1e-8;
const int inf=0x3f3f3f3f;
const LL linf=0x3f3f3f3f3f3f3f3f;
#define MOD 1000000007
using namespace std;

struct mat{
    long long a[30][30];
    int r,c;
    mat operator *(const mat &b)const{
        mat ret;
        for (int i=0;i<r;i++){
            for (int j=0;j<b.c;j++){
                ret.a[i][j]=0;
                for (int k=0;k<c;k++)
                    ret.a[i][j]+=a[i][k]*b.a[k][j],ret.a[i][j]%=MOD;
            }
        }
        ret.r = r;
        ret.c = bc;
        return ret;
    }
    mat init_unit(int x)
    {
        r=c=x;
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                if(i==j)a[i][j]=1;
                else a[i][j]=0;
            }
        }
    }
}unit;

mat pow(mat p,int n){
    unit.init_unit(3);
    mat ans=unit;
    while(n){
        if(n&1)ans=p*ans;
        p=p*p;
        n>>=1;
    }
    return ans;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        if(n<4)puts("1");
        else{
            mat p;
            memset(&p,0,sizeof p);
            p.r=p.c=3;
            p.a[0][1]=p.a[1][2]=p.a[2][0]=p.a[2][2]=1;
            mat years = pow(p,n- 3 );
            p.a[0][0]=p.a[1][0]=p.a[2][0]=1;
            p.c=1;
            years =years* p;
            printf("%lld\n",ans.a[2][0]);
        }
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250128&siteId=291194637