矩阵快速幂

· · 个人记录

先上代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#define mod 1000000007
#define ll long long
#define res register 
using namespace std;
struct node{
    ll s[4][4];
}w;
inline long long read(){
    ll s=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')
          w=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        s=s*10+ch-48;
        ch=getchar();
    }
    return s*w;
}
inline node change(node x,node y){
    node c;
    memset(c.s,0,sizeof(c.s));
    for(res int i=1;i<=3;i++)
      for(res int j=1;j<=3;j++)
        for(res int k=1;k<=3;k++){
            c.s[i][j]+=(x.s[i][k]*y.s[k][j])%mod;
            c.s[i][j]%=mod;
        }
    return c;
}
inline node fast(node x,ll y){
    node ans=x;
    if(y<=1)
      return x;
    y--;
    while(y>0){
        if(y&1)
          ans=change(ans,x);
        x=change(x,x);
        y/=2;
    }
    return ans;
}
int main(){
    int t;
    t=read();
    memset(w.s,0,sizeof(w));
    w.s[1][1]=w.s[3][1]=w.s[1][2]=w.s[2][3]=1;
    while(t--){
        int k;
        k=read();
        node q;
        memset(q.s,0,sizeof(q.s));
        q=fast(w,k-1);
        cout<<q.s[1][1]<<endl;
    }
    return 0;
}

跑了38ms,不是很快……

改天补讲解

P1939

矩阵快速幂的主要作用在于优化。当你要求一个数列的10的n次方项时,由于1000ms的时限,绝对会线性爆炸。于是我们考虑加速。

模板:P1939数列加速

首先,对于矩阵乘法,不相当于普通的横纵坐标一一对应的相乘,所以我们要写独特的change函数来模拟矩阵乘法。然后根据快速幂的套路,一次次算就好了……

可惜,难点不在这……

问题在于,对于每一题,都有其独特的单位矩阵,需要自己推。例如上面我的单位矩阵,ans是1,1。题目难度的不同,考验的点也是不同的。

讲解考完期末补吧……

2019.1.17, 期末考试day 1

复杂度为O(log2n^2)

2019.1.18

考试完了……

两天考试挂了,luogu你tm告诉我是中平……

凉啦……凉啦……

先打上普通快速幂模板: ```cpp #include<cstdio> #include<iostream> using namespace std; inline long long fast(int a,int b){ int ans=1,base=a; while(b){ if(b&1) ans*=base; base*=base; b>>=1; } return ans; } int main(){ int a,b; cin>>a>>b; cout<<fast(a,b)<<endl; return 0; } ``` 然而,矩阵快速幂的思想与之相同,唯一不同在于* 的变化 给出矩阵乘函数: ```cpp struct node{//三阶矩阵相乘 int s[4][4]; }; inline node change(node a,node b){ node c; for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) c.s[i][j]=0; for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) for(int k=1;k<=3;k++){ c.s[i][j]+=a.s[i][k]*b.s[k][j]; } return c; } ``` 不带取模的模板 至于矩阵乘的过程,我就不模拟了…… 所以,我们也知道了$fast$函数的写法啦…… # $fast: See You Later!