标签:
http://acm.hdu.edu.cn/showproblem.php?pid=2243
2 3 aa ab 1 2 a
104 52
/***
hdu2243 ac自动机+矩阵连乘
题目大意:给定n个单词,求长度不大于m的字符串中所有含给定单词的字符串的个数
解题思路:利用ac自动机可以够造出矩阵,矩阵的几次幂就可以统计长度为多少的所有不含模式串的字符串的个数。然后,矩阵加一列,并给该列的数全部赋1,
就可以在转移过程中统计出前缀和(很巧妙的)。然后用总的个数减去所有不含模式串的就是所有含模式串的。总的个数求法见代码注释。个数需要
对2^64取余,直接定义unsigned long long 让其自然溢出就可以了
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
typedef unsigned long long ULL;
struct Matrix///构造矩阵
{
ULL mat[40][40];
int n;
Matrix() {}
Matrix(int _n)
{
n=_n;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
mat[i][j]=0;
}
}
}
Matrix operator *(const Matrix &b)const
{
Matrix ret=Matrix(n);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
for(int k=0; k<n; k++)
{
ret.mat[i][j]+=mat[i][k]*b.mat[k][j];
}
}
}
return ret;
}
};
ULL pow_m(ULL a,int n)///快速幂
{
ULL ret=1;
ULL tmp=a;
while(n)
{
if(n&1)ret*=tmp;
tmp*=tmp;
n>>=1;
}
return ret;
}
Matrix pow_M(Matrix a,int n)///矩阵快速幂
{
Matrix ret=Matrix(a.n);
for(int i=0; i<a.n; i++)
{
ret.mat[i][i]=1;
}
Matrix tmp=a;
while(n)
{
if(n&1)ret=ret*tmp;
tmp=tmp*tmp;
n>>=1;
}
return ret;
}
struct Trie
{
int next[40][26],fail[40];
bool end[40];
int root,L;
int newnode()
{
for(int i=0; i<26; i++)
next[L][i]=-1;
end[L++]=false;
return L-1;
}
void init()
{
L=0;
root=newnode();
}
void insert(char *buf)
{
int len=strlen(buf);
int now=root;
for(int i=0; i<len; i++)
{
if(next[now][buf[i]-'a']==-1)
next[now][buf[i]-'a']=newnode();
now=next[now][buf[i]-'a'];
}
end[now]=true;
}
void build()
{
queue<int>Q;
fail[root]=root;
for(int i=0; i<26; i++)
{
if(next[root][i]==-1)
{
next[root][i]=root;
}
else
{
fail[next[root][i]]=root;
Q.push(next[root][i]);
}
}
while(!Q.empty())
{
int now=Q.front();
Q.pop();
if(end[fail[now]])end[now]=true;
for(int i=0; i<26; i++)
{
if(next[now][i]==-1)
{
next[now][i]=next[fail[now]][i];
}
else
{
fail[next[now][i]]=next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
Matrix getMatrix()///获得状态转移矩阵,加一列,每次相乘可以求前面所有数的和mat[0][L+1]
{
Matrix ret=Matrix(L+1);
for(int i=0; i<L; i++)
{
for(int j=0; j<26; j++)
{
if(end[next[i][j]]==false)
ret.mat[i][next[i][j]]++;
}
}
for(int i=0; i<L+1; i++)
{
ret.mat[i][L]=1;
}
return ret;
}
} ac;
char buf[10];
int main()
{
int n,L;
while(~scanf("%d%d",&n,&L))
{
ac.init();
for(int i=0; i<n; i++)
{
scanf("%s",buf);
ac.insert(buf);
}
ac.build();
Matrix a=ac.getMatrix();
a=pow_M(a,L);
ULL res=0;
for(int i=0; i<a.n; i++)
{
res+=a.mat[0][i];
}
res--;
/*
* f[n]=1 + 26^1 + 26^2 +...26^n
* f[n]=26*f[n-1]+1
* {f[n] 1} = {f[n-1] 1}[26 0;
1 1]
* 数是f[L]-1;
* 此题的L<2^31.矩阵的幂不能是L+1次,否则就超时了
*/
a=Matrix(2);
a.mat[0][0]=26;
a.mat[1][0]=a.mat[1][1]=1;
a=pow_M(a,L);
ULL ans=a.mat[1][0]+a.mat[0][0];
ans--;
ans-=res;
cout << ans<<endl;
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/lvshubao1314/article/details/45396509