题目:
分析:
数位dp是从高位开始依次选数字,这和AC自动机的多模式字符串依次匹配是一致的,只是把匹配函数改成了数位dp,依次选的数字相当于主串,等价于在AC自动机上判断主串是否包含了子串,我们需要记录每次选了一个数字后,到达了AC自动机上的那个节点,对于每次选的数字x,那么之后到达的节点就是tire[root][x],我们只需要判断这个节点是否被标记即可,同时要标记前导0,因为具有前导0的数不计入,所以AC自动机不能从前导0就开始匹配
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 2e3+14;
const int mod = 1e9+7;
char s[MAXN],dit[MAXN];
int tire[MAXN][10],num[MAXN],fail[MAXN],cnt,m,LEN;
void init(int x)
{
for(int i = 0;i < 10; ++i) tire[x][i] = 0;
num[x] = 0;
}
void Build_ac(char *s)
{
int root = 0,len = strlen(s);
for(int i = 0;i < len; ++i){
int t = s[i] - '0';
if(!tire[root][t]){
tire[root][t] = ++cnt;
init(cnt);
}
root = tire[root][t];
}
num[root]++;
}
void Get_fail()
{
queue<int> p;
for(int i = 0; i < 10; ++i){
int son = tire[0][i];
if(son){
fail[son] = 0;
p.push(son);
}
else tire[0][i] = 0;
}
while(!p.empty())
{
int x = p.front();p.pop();
num[x] |= num[fail[x]]; //整合x节点匹配成功和匹配失败后到达节点的标记信息,因为可能在其他节点匹配成功
for(int i = 0; i < 10; ++i){
if(tire[x][i]){
fail[tire[x][i]] = tire[fail[x]][i];
p.push(tire[x][i]);
}
else tire[x][i] = tire[fail[x]][i];
}
}
}
LL dp[MAXN][MAXN];
LL dfs(int pos,int root,int ZERO,int limit){
if(pos >= LEN) return 1;
if(!limit && ~dp[pos][root]) return dp[pos][root];
int up = limit ? (int)(dit[pos]-'0') : 9;
LL res = 0;
for(int i = 0;i <= up; ++i){
if(num[tire[root][i]]) continue; //选择i后已经包含了某些子串就不能选
res += dfs(pos+1,(ZERO&&!i)?0:tire[root][i],ZERO&&!i,(char)(i+'0')==dit[pos]&&limit);
res %= mod;
}
if(!limit) dp[pos][root] = res;
return res;
}
LL solve(){
LEN = strlen(dit);
return dfs(0,0,1,1);
}
int main()
{
scanf("%s %d",dit,&m);
while(m--){
scanf("%s",s);
Build_ac(s);
}
Get_fail();
memset(dp,-1,sizeof(dp));
printf("%lld",(solve()-1+mod)%mod);
return 0;
}