对于特定的长度为的字符串,容易发现如果是一个禁忌字符串,那么答案马上可以加一
然后单独再对计算贡献,这样一定最优.
于是使用自动机压缩一下个字符串的状态,定义表示前个字符匹配到位置的概率
每次枚举字母,设状态通过字母可以转移到状态
当为终止节点时,设
且
当不为终止节点时
时间复杂度,其中表示自动机上的点数,大概在左右
注意到每次的转移是一样的,于是可以用矩阵来转移
初始矩阵为
其中表示当前在自动机节点的概率,表示现在的答案
转移矩阵是一个的矩阵
当状态能通过字母转移到状态时
特殊的,对于最后一列是计算答案用的,设状态能通过字母转移到终止节点
那么
且,这是为了继承上一轮计算的
#include <bits/stdc++.h>
using namespace std;
#define Lf long double
const int maxn =3e5+10;
int zi[maxn][30],fail[maxn],id,val[maxn];
int n,len,alp,mx;
char s[maxn];
struct rce
{
Lf a[109][109];
rce(){ memset(a,0,sizeof a ); }
rce operator * ( const rce&b ) const
{
rce s;
for(int i=0;i<=mx;i++)
for(int j=0;j<=mx;j++)
{
s.a[i][j] = 0;
for(int k=0;k<=mx;k++)
s.a[i][j] += a[i][k]*b.a[k][j];
}
return s;
}
};
rce quick(rce a,int n)
{
rce ans = a;
for( ; n ; n>>=1,a = a*a )
if( n&1 ) ans = ans*a;
return ans;
}
void insert(char s[])
{
int le = strlen( s+1 ), now = 0;
for(int i=1;i<=le;i++)
{
if( zi[now][s[i]-'a']==0 ) zi[now][s[i]-'a'] = ++id;
now = zi[now][s[i]-'a'];
}
val[now] = 1;//这个位置有字符串存在
}
void make_fail()
{
queue<int>q;
for(int i=0;i<=25;i++)
if( zi[0][i] ) q.push( zi[0][i] );
while( !q.empty() )
{
int u = q.front(); q.pop();
for(int i=0;i<=25;i++)
{
if( zi[u][i] )//存在这个节点
fail[zi[u][i]] = zi[fail[u]][i],q.push( zi[u][i] );
else
zi[u][i] = zi[fail[u]][i];
}
}
}
int main()
{
cin >> n >> len >> alp;
for(int i=1;i<=n;i++)
{
scanf("%s",s+1 );
insert( s );
}
make_fail(); mx = id+1;
Lf proalp = 1.0/alp;
rce chu, zhuan;
chu.a[0][0] = 1;
for(int q=0;q<=id;q++)//枚举状态
for(int j=0;j<alp;j++)
{
int nxt = zi[q][j];
if( val[nxt] )
{
zhuan.a[q][0] += proalp;
zhuan.a[q][id+1] += proalp;
}
else//不是终止状态
zhuan.a[q][nxt] += proalp;
}
zhuan.a[id+1][id+1] = 1;
chu = chu*quick( zhuan,len-1 );
printf("%.7Lf",chu.a[0][id+1] );
}