题意:
给一些模式串。
再给n个字符和它们出现的概率,问用这些字符随机构造一个长为L的字符串,不包含任意一个模式串的概率是多少。
做法:
用模式串建ac自动机。
然后问题相当于从字典树的根开始跑,不经过任意一个单词结尾的节点跑L步的概率。
我们把单词结尾的节点打标记。假如一个点对应的fail节点也打了标记,它也要打上标记,因为以这个节点为结尾的后缀在模式串中出现过。
定义f[i][j]表示在第i个节点,之后还要走j步不经过打标记的节点的概率。
然后你枚举转移的字符,如果没打标记就转移过去。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<queue>
using namespace std;
const int N = 1010;
int n, tot, L;
int c[N][N], v[N], fail[N], vis[N][N];
double f[N][N], p[N];
char s[N], ch[N][5];
inline int id(int x)
{
if(x >= 'a') return x-'a'+36;
else if(x >= 'A') return x-'A'+10;
else return x-'0';
}
inline void insert(char s[])
{
int len = strlen(s), o = 1;
for(int i = 0; i < len; i ++) {
int t = id(s[i]);
if(!c[o][t]) c[o][t] = ++ tot;
o = c[o][t];
}
v[o] = 1;
}
inline void build()
{
queue<int> q;
for(int i = 0; i < 62; i ++) c[0][i] = 1; q.push(1);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i = 0; i < 62; i ++) if(c[u][i]) {
fail[c[u][i]] = c[fail[u]][i];
q.push(c[u][i]);
v[c[u][i]] |= v[fail[c[u][i]]];
} else c[u][i] = c[fail[u]][i];
}
}
inline double dp(int u, int l)
{
if(l == 0) return 1;
if(!u) u = 1;
if(vis[u][l]) return f[u][l];
vis[u][l] = 1;
double ret = 0;
for(int i = 1; i <= n; i ++) {
int t = id(ch[i][0]);
if(!v[c[u][t]]) ret += p[t]*dp(c[u][t], l-1);
}
f[u][l] = ret;
return ret;
}
int main()
{
int Test, cas; scanf("%d", &Test);
while(Test --) {
scanf("%d", &n); tot = 1; memset(c, 0, sizeof c); memset(fail, 0, sizeof fail); memset(v, 0, sizeof v);
for(int i = 1; i <= n; i ++) { scanf("%s", s); insert(s); }
build();
memset(p, 0, sizeof p);
scanf("%d", &n);
for(int i = 1; i <= n; i ++) { scanf("%s", ch[i]); scanf("%lf", &p[id(ch[i][0])]); }
scanf("%d", &L);
memset(f, 0, sizeof f); memset(vis, 0, sizeof vis);
printf("Case #%d: %.6lf\n", ++ cas, dp(1, L));
}
return 0;
}