题意
给出n个单词。若一个字符串至少包含一个单词,就称这个字符串是”可读的”。
求长度为m的”可读的”字符串个数。所有字符都在[A,Z]范围。
n,|s|<=60,m<=100
题解
首先一步转化,我们从补集考虑统计ans表示一个单词都不包含的串数,则答案为
m26−ans
。
多串匹配问题肯定要想到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;
}