题解
dp递推式列出来后表示成转移矩阵,对于每一位数左移位数不同时逐次处理即可。 ,最多算18次。
代码
#include<cstdio>
using namespace std;
typedef long long ll;
ll n,pow[20];int mod,l;
struct mat{
int a[5][5];
inline void itia(){
for(int j,i=1;i<=3;++i)
for(j=1;j<=3;++j)
a[i][j]=0;
}
inline void ori(){
for(int i=1;i<=3;++i) a[i][i]=1;
}
}A,B,C,ty;
mat mul(mat x,mat y){
ty.itia();
for(int k,j,i=1;i<=3;++i)
for(j=1;j<=3;++j)
for(k=1;k<=3;++k)
ty.a[i][j]=(ty.a[i][j]+1ll*x.a[i][k]*y.a[k][j]%mod)%mod;
return ty;
}
mat fp(mat x,ll b){
mat ret;ret.itia();ret.ori();
while(b){
if(b&1) ret=mul(ret,x);
x=mul(x,x);
b>>=1;
}
return ret;
}
int main(){
int i,j;
pow[0]=1;for(i=1;i<=18;++i) pow[i]=pow[i-1]*10;
scanf("%lld%d",&n,&mod);
A.itia();A.a[1][1]=1%mod;A.a[1][2]=A.a[1][3]=1;
for(ll temp=n/10;temp;temp/=10) l++;
B.itia();B.a[2][1]=B.a[2][2]=1;
for(i=1;i<=3;++i) B.a[3][i]=1;
for(i=0;i<l;++i){
B.a[1][1]=pow[i+1]%mod;
if(!i)A=mul(A,fp(B,8));
else A=mul(A,fp(B,pow[i+1]-pow[i]));
}
B.a[1][1]=pow[l+1]%mod;
if(l)A=mul(A,fp(B,n-pow[l]+1));
else A=mul(A,fp(B,n-1));
printf("%d\n",A.a[1][1]);
}