BZOJ----3530:数数【AC自动机上数位dp】

题目:

戳这里~~

分析:

数位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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值