题意
给定一个长为 的数字串 ,你要把它分成若干块。设分完后的第 块数字为 ,定义 表示把 分成不小于 的数字和的方案数,求 。
。
思路
先考虑怎么求 。
由于是不小于 的数字和,于是
那不就能直接矩快了吗?
我们知道 ,其中
设一种划分方案的各块值为 ,则
,可以用 DP!
设 表示数字串 从 到 顺次拼成的数字, 表示考虑到第 位时的 ,那么转移时有
(注意 是矩阵)
答案就是 。
怎么快速求 呢?
如果我们求出了 ,那么
于是我们固定 从前往后扫即可。
时间复杂度:,常数巨大。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e3+5,mod=1e9+7;
struct Matrix{//矩阵
int n,m,a[3][3];
Matrix operator * (const Matrix x) const{
Matrix ans=Matrix{n,x.m,{}};
for(int i=0;i<n;i++)
for(int j=0;j<x.m;j++)
for(int t=0;t<m;t++)
ans.a[i][j]=(ans.a[i][j]+a[i][t]*x.a[t][j])%mod;
return ans;
}//矩阵乘法
Matrix operator + (const Matrix x) const{
Matrix ans=Matrix{n,m,{}};
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
ans.a[i][j]=(a[i][j]+x.a[i][j])%mod;
return ans;
}//矩阵加法
}W[10],A,I,dp[N];
char c[N];
int n;
void init(){
A=Matrix{1,2,{{1,0}}};//A
I=Matrix{2,2,{{1,0},{0,1}}};//单位矩阵
for(int i=1;i<=n;i++) dp[i].n=dp[i].m=2;
dp[0]=I;//dp 初始化
W[0]=I;
W[1]=Matrix{2,2,{{0,1},{1,1}}};
for(int i=2;i<10;i++) W[i]=W[i-1]*W[1];//W^i
}
Matrix pow10(Matrix x){
Matrix t=x*x*x;
return t*t*t*x;//优化一点常数
}
signed main(){
scanf("%lld %s",&n,c+1);
init();
for(int l=1;l<=n;l++){
Matrix s=I;
for(int r=l;r<=n;r++){
s=pow10(s)*W[c[r]-'0'];
dp[r]=dp[r]+s*dp[l-1];//转移
}
}
cout<<(A*dp[n]).a[0][0]<<'\n';
return 0;
}