• P1939 【模板】矩阵加速(数列)


    题意:矩阵加速

    思路:可以看这篇博客,里面有一个结论 https://www.cnblogs.com/Mrsrz/p/7629374.html

    代码:

    #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=b.c;
            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 ans=pow(p,n-3);
                p.a[0][0]=p.a[1][0]=p.a[2][0]=1;
                p.c=1;
                ans=ans*p;
                printf("%lld
    ",ans.a[2][0]);
            }
        }
        return 0;
    }
  • 相关阅读:
    C# 规格说明书
    C#学习笔记----复习笔记
    C#学习笔记-stream,win8.1开发小记
    C#学习笔记-Win8.1 store app winform开发小记
    C#学习笔记:linq和xml
    C#第六周--关于正则表达式应用,delegates关键字
    C#第六课---struct,interface
    C#第五课--继承和多态
    开发了一款小程序
    「CSS Warning 2」icon 的做法
  • 原文地址:https://www.cnblogs.com/lalalatianlalu/p/8989889.html
Copyright © 2020-2023  润新知