给至多6个字符串,每个长度不超过5,问长度不超过L(L<2^31)的字符串中,有多少个有以这些字符串中至少一个为子串。
先建立AC自动机,然后构造状态转移矩阵,然后用矩阵加速计算。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int K=26;
const int N=40;
struct Node {
Node *ch[K],*fail;
int match,count;
Node () {
memset(this,0,sizeof(Node));
}
void *operator new(size_t,void *p) {
return p;
}
};
Node *que[N];
Node b[N],*root,*superRoot,*bp;
void clear() {
bp=b;
superRoot=new(bp++)Node();
root=new(bp++)Node();
root->fail=superRoot;
for (int i=0;i<K;i++) superRoot->ch[i]=root;
superRoot->match=-1;
}
void insert(char *s) {
Node *t=root;
for (;*s;s++) {
int x=*s-'a';
if (t->ch[x]==NULL) t->ch[x]=new(bp++)Node();
t=t->ch[x];
}
t->match++;
}
void build() {
int p=0,q=0;
que[q++]=root;
while (p!=q) {
Node *t=que[p++];
if (t!=root) t->match+=t->fail->match;
for (int i=0;i<K;i++) {
if (t->ch[i]) {
t->ch[i]->fail=t->fail->ch[i];
que[q++]=t->ch[i];
} else t->ch[i]=t->fail->ch[i];
}
}
}
struct Matrix {
int n;
unsigned long long a[40][40];
Matrix (int nn=0) {
n=nn;
memset(a,0,sizeof(a));
}
friend Matrix operator * (const Matrix &a,const Matrix &b) {
Matrix c;
int n=c.n=a.n;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
for (int k=0;k<n;k++)
c.a[i][j]+=a.a[i][k]*b.a[k][j];
return c;
}
};
Matrix pow(const Matrix &x,int n) {
if (n==1) return x;
Matrix ans=pow(x,n>>1);
ans=ans*ans;
if (n&1) ans=ans*x;
return ans;
}
int n,l,m;
char s[10];
Matrix c,ans;
void constructMatrix() {
c=Matrix();
c.a[0][0]=1;
c.a[0][1]=1;
c.a[1][1]=K;
m=2;
for (Node *t=root;t!=bp;t++) if (!t->match) t->count=m++;
for (Node *t=root;t!=bp;t++)
if (!t->match)
for (int k=0;k<K;k++)
if (t->ch[k]->match) c.a[1][t->count]++;
else c.a[t->ch[k]->count][t->count]++;
c.n=m;
//for (int i=0;i<m;i++) {
//for (int j=0;j<m;j++) printf("%llu ",c.a[i][j]);
//printf("\n");
//}
}
int main() {
int i;
while (scanf("%d%d",&n,&l)!=EOF) {
clear();
for (i=0;i<n;i++) {
scanf("%s",s);
insert(s);
}
build();
constructMatrix();
ans=pow(c,l);
printf("%llu\n",ans.a[0][2]+ans.a[1][2]);
}
return 0;
}