P3216 [HNOI2011]数学作业 题解

· · 个人记录

题目传送门

在学习矩阵之前,我看过这道题,然而没什么思路。学完之后立刻就懂了。

首先我们知道矩阵优化是用来优化递归数列的,所以我们可以把这个东西弄成一个递推数列。下面的 \text{C}(n) 就是题目中的 \text{Concatenate}(n) 。

\text{C}(n)=\begin{cases}\text{C}(n-1)\times 10^1+n&[1\le n \le 9]\\\text{C}(n-1)\times 10^2+n&[10\le n \le 99]\\\text{C}(n-1)\times 10^3+n&[100\le n\le 999]\\\cdots\cdots\end{cases}

这样就变成了很多个的递推数列了。将每一个递推数列变换的矩阵都求出来,再乘起来就行了。

例如:

\begin{bmatrix}\text{C}(n-1)\\n-1\\1\end{bmatrix}\xrightarrow{A_1}\begin{bmatrix}\text{C}(n)\\n\\1\end{bmatrix}\quad [1\le n\le 9]

解得:

A_1=\begin{bmatrix}10&1&1\\0&1&1\\0&0&1\end{bmatrix}
\begin{bmatrix}\text{C}(n-1)\\n-1\\1\end{bmatrix}\xrightarrow{A_2}\begin{bmatrix}\text{C}(n)\\n\\1\end{bmatrix}\quad [10\le n\le 99]

解得:

A_2=\begin{bmatrix}100&1&1\\0&1&1\\0&0&1\end{bmatrix} \cdots\cdots\cdots\cdots

然后初始向量为:

\overrightarrow{s}=\begin{bmatrix}0\\0\\1\end{bmatrix}

所以答案为:

\begin{bmatrix}\text{C}(n)\\n\\1\end{bmatrix}=......A_2^{90}A_1^9\begin{bmatrix}0\\0\\1\end{bmatrix} \color{red}\texttt{Talk is easy,show me the Code:}
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=7;
int L=3;
ll n,base=1,mod,ans;
struct Matrix
{
    ll M[N][N];
    void clear(){memset(M,0,sizeof(M));}
    void reset(){for(int i=1;i<=L;i++)M[i][i]=1;}
    Matrix(bool isT){clear();if(isT)reset();}
    Matrix friend operator *(const Matrix A,const Matrix B)
    {
        Matrix Ans(0);
        for(int i=1;i<=L;i++)
            for(int j=1;j<=L;j++)
                for(int k=1;k<=L;k++)
                    Ans.M[i][j]=(Ans.M[i][j]+A.M[i][k]*B.M[k][j])%mod;
        return Ans;
    }
};
Matrix QuickPow(Matrix T,ll p)
{
    Matrix Ans(1);
    while(p)
    {
        if(p&1)Ans=Ans*T;
        T=T*T;p>>=1;
    }
    return Ans;
}
Matrix ANS(1),a(0);
void work(ll l,ll r)
{
    a.clear();
    a.M[1][1]=(base*10)%mod;a.M[1][2]=a.M[1][3]=1;
    a.M[2][2]=1;a.M[2][3]=1;
    a.M[3][3]=1;
    a=QuickPow(a,r-l+1);
    ANS=a*ANS;//请注意这里不是ANS=ANS*a 要使用左乘的方式 
}
int main(){
    scanf("%lld%lld",&n,&mod);
    while(base<n){work(base,min(base*10-1,n));base*=10;}
    ans=ANS.M[1][3];
    if(base==n)ans=((ans*(base%mod))%mod*10+n)%mod;//为预防n=10^18特地这样写的 
    printf("%lld",ans);
    return 0;
}
\color{red}\text{一个需要注意的地方就是看乘矩阵的时候有没有反了。。。}

然后这道题就AC了。献上提交记录