【题解】Luogu P4838 P哥破解密码

原题传送门

考虑一个一个将字母加入字符串后面

\(f[i][0/1/2]\)表示长度为\(i\)字符串末尾有\(0/1/2\)个A的种类数

易知:

\(f[1][0]=1,f[1][1]=1,f[1][2]=0\)

\(f[i][0]=f[i-1][0]+f[i-1][1]+f[i-1][2]\)

\(f[i][1]=f[i-1][0]\)

\(f[i][2]=f[i-1][1]\)

发现这个递推式子珂以用矩阵乘法

\[ \left[ \begin{matrix} f[i][0] & f[i][1] & f[i][2] \end{matrix} \right] * \left[ \begin{matrix} 1 & 1 & 0 \\ 1 & 0 & 1 \\ 1 & 0 & 0 \end{matrix} \right] = \left[ \begin{matrix} f[i+1][0] & f[i+1][1] & f[i+1][2] \end{matrix} \right] \]

矩阵快速幂即可,答案是\(f[n][0]+f[n][1]+f[n][2]\)

#include <bits/stdc++.h>
#define mod 19260817
//#define getchar nc
using namespace std;
inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int read()
{
    register int x=0,f=1;register char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return x*f;
}
inline void write(register int x)
{
    if(!x)putchar('0');if(x<0)x=-x,putchar('-');
    static int sta[20];register int tot=0;
    while(x)sta[tot++]=x%10,x/=10;
    while(tot)putchar(sta[--tot]+48);
}
struct mat{
    int a[3][3];
    inline mat()
    {
        memset(a,0,sizeof(a));
    }
    inline mat operator*(const mat&b)const{
        mat c;
        for(register int i=0;i<3;++i)
            for(register int j=0;j<3;++j)
                for(register int k=0;k<3;++k)
                    c.a[i][j]=(c.a[i][j]+1ll*a[i][k]*b.a[k][j])%mod;
        return c;
    }
}s,o,ans;
inline mat fastpow(register mat a,register int b)
{
    mat res;
    res.a[0][0]=res.a[1][1]=res.a[2][2]=1;
    while(b)
    {
        if(b&1)
            res=res*a;
        a=a*a;
        b>>=1;
    }
    return res;
}
int T,n;
int main()
{
    T=read();
    s.a[0][0]=s.a[1][0]=s.a[2][0]=s.a[0][1]=s.a[1][2]=1;
    o.a[0][0]=o.a[0][1]=1;
    while(T--)
    {
        n=read();
        ans=o*fastpow(s,n-1);
        write((ans.a[0][0]+ans.a[0][1]+ans.a[0][2])%mod),puts("");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/yzhang-rp-inf/p/10890935.html