[AC自动机 + DP] BZOJ1030: [JSOI2007]文本生成器

题意

给出n个单词。若一个字符串至少包含一个单词,就称这个字符串是”可读的”。
求长度为m的”可读的”字符串个数。所有字符都在[A,Z]范围。
n,|s|<=60,m<=100

题解

首先一步转化,我们从补集考虑统计ans表示一个单词都不包含的串数,则答案为 m26ans
多串匹配问题肯定要想到AC自动机。
我们要求的是长度为m的字符串没有匹配任何串的方案数。
长度对应AC自动机上走的次数。
没有匹配任何串对应不能走(a[i]->cnt||a[i]->last!=root)的点a[i]。
f[i][j] 表示在AC自动机上走了i步,目前位置在j的方案数,简单DP一下即可。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=6005, maxm=105, MOD=10007;
struct node{
    int cnt,id; node *fail,*last;
    node(node* son=NULL){ id=cnt=0; last=fail=son; for(int i=0;i<=25;i++) ch[i]=son; }
    node* ch[27];
} nil, *null=&nil, *root=null, *a[maxn];
int tot;
typedef node* P_node;
void Insert(P_node &p,char *now){
    if(p==null) p=new node(null), a[++tot]=p, p->id=tot;
    if((*now)=='\000'){ p->cnt++; return; }
    Insert(p->ch[(*now)-'A'],now+1);
}
queue<P_node> que;
void build(){
    root->fail=root->last=root;
    for(int i=0;i<=25;i++) if(root->ch[i]!=null){
        P_node v=root->ch[i]; que.push(v); 
        v->fail=v->last=root;
    } else root->ch[i]=root;
    while(!que.empty()){
        P_node p=que.front(); que.pop();
        for(int i=0;i<=25;i++) if(p->ch[i]!=null){
            P_node v=p->ch[i]; que.push(v);
            v->fail=p->fail->ch[i];
            v->last=(v->fail->cnt?v->fail:v->fail->last);  
        } else p->ch[i]=p->fail->ch[i];
    }
}
int n,m,ans,f[maxm][maxn];
bool vis[maxn];
char st[105];
int main(){
    freopen("bzoj1030.in","r",stdin);
    freopen("bzoj1030.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%s",st), Insert(root,st);
    build();
    f[0][1]=1; for(int i=1;i<=tot;i++) vis[i]=(a[i]->cnt||a[i]->last!=root);
    for(int i=1;i<=m;i++) 
     for(int j=1;j<=tot;j++) if((!vis[j])&&f[i-1][j])
      for(int k=0;k<=25;k++) f[i][a[j]->ch[k]->id]=(f[i][a[j]->ch[k]->id]+f[i-1][j])%MOD;
    ans=1; for(int i=1;i<=m;i++) ans=(ans*26)%MOD;
    for(int i=1;i<=tot;i++) if(!vis[i]) ans=(ans-f[m][i])%MOD;
    printf("%d\n",(ans+MOD)%MOD); 
    return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值