http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=31655
大白上的题。
AC自动机经典题型。
论如何忘记写getfail()。
/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef double DB;
const int maxnode = 405, maxn = 105, maxl = 105, M = 61, maxq = 10000;
const DB eps = 1e-9;
int q[maxq];
DB pro[maxn], dp[maxnode][maxl];
bool vis[maxnode][maxl];
inline int getid(char ch) {
if(ch >= 'a' && ch <= 'z') return ch - 'a';
if(ch >= 'A' && ch <= 'Z') return ch - 'A' + 26;
if(ch >= '0' && ch <= '9') return ch - '0' + 52;
}
struct _acm {
int son[maxnode][maxn], acmcnt, fail[maxnode];
bool flag[maxnode];
void init() {
memset(son, 0, sizeof(son)); acmcnt = 0;
for(int i = 0; i < maxnode; i++) fail[i] = flag[i] = 0;
}
void insert(char *s) {
int now = 0, len = strlen(s);
for(int i = 0; i < len; i++) {
int &pos = son[now][getid(s[i])];
if(!pos) pos = ++acmcnt;
now = pos;
}
flag[now] = 1;
}
void getfail() {
int h = 0, t = 0;
for(int i = 0; i <= M; i++) if(son[0][i]) q[t++] = son[0][i];
while(h != t) {
int u = q[h++];
for(int i = 0; i <= M; i++)
if(!son[u][i]) son[u][i] = son[fail[u]][i];
else {
fail[q[t++] = son[u][i]] = son[fail[u]][i];
flag[son[u][i]] |= flag[fail[son[u][i]]];
}
}
}
DB dfs(int u, int L) {
if(!L) return 1.0;
if(vis[u][L]) return dp[u][L];
vis[u][L] = 1; dp[u][L] = 0.0;
for(int i = 0; i <= M; i++)
if(!flag[son[u][i]]) dp[u][L] += pro[i] * dfs(son[u][i], L - 1);
return dp[u][L];
}
} acm;
char str[maxn];
int main() {
int T; scanf("%d", &T);
for(int cas = 1; cas <= T; cas++) {
acm.init();
memset(vis, 0, sizeof(vis));
for(int i = 0; i <= M; i++) pro[i] = 0.0;
int m; scanf("%d", &m);
for(int i = 1; i <= m; i++) {
scanf("%s", str);
acm.insert(str);
}
acm.getfail();
scanf("%d", &m);
for(int i = 1; i <= m; i++) {
DB x;
scanf("%s%lf", str, &x);
pro[getid(str[0])] = x;
}
scanf("%d", &m);
printf("Case #%d: %.6lf\n", cas, acm.dfs(0, m));
}
return 0;
}