原题网址:
http://acm.hust.edu.cn/vjudge/problem/31655
题意: 给出一些字符和各自对应的选择概率,随机选择L次后将得到一个长度为L的随机字符串S(每次独立随机)。
给出K个模板串,计算S不包含任何一个模板串的概率(即任何一个模板串都不是S的连续子串)。
题解:ac自动机 + dp
重点是dp。。。仔细看看哪一段的代码好了。
#include <iostream>
using namespace std;
#include <cstdio>
#include <string.h>
#include <queue>
#define maxnode 10000// maxnode 一般设置为 模式串数量*模式串长度
#define sigma 62
struct ac_automation{
int ch[maxnode][sigma];
int val[maxnode];
//int cnt[maxnode]; // count
int last[maxnode];
int f[maxnode]; // fail指针
int sz; // the num of the trie
int ans; // answer
void clear(){
sz = 1;
ans = 0;
memset(ch[0],0,sizeof(ch[0]));
memset(val,0,sizeof(val));
//memset(cnt,0,sizeof(cnt));
}
int idx(char c) {
if (c >= 'a' && c <= 'z') return c - 'a';
if (c >= 'A' && c <= 'Z') return c - 'A' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
}
void insert(char s[],int v){
int u = 0;
for(int i = 0; s[i];i++){
int c = idx( s[i] );
if(!ch[u][c]){
memset(ch[sz],0,sizeof(ch[sz]));
ch[u][c] = sz++;
}
u = ch[u][c];
}
//cnt[u]++;
val[u] = v;
}
void build(){
queue<int> q;
f[0] = 0;
for(int i = 0;i < sigma;i++){
if(ch[0][i]){
f[ch[0][i]] = 0;
q.push(ch[0][i]);
last[ch[0][i]] = 0;
}
}
while(!q.empty()){
int now = q.front();
q.pop();
for(int i = 0;i < sigma ;i++){
int son = ch[now][i];
if(!son){
ch[now][i] = ch[f[now]][i];
continue;
}
q.push(son);
f[son] = ch[f[now]][i];
last[son] = val[f[son]] ? f[son] : last[f[son]];
if(last[son]){ // 如果他的上一层是禁止的,那么他也得禁止
val[son] = 1;
}
}
}
}
}ac;
bool vis[420][110]; //记忆化搜索
double dp[420][110];
double p[65];//各个字符的概率
double dfs(int u,int l){ l 代表第l个位置
if(vis[u][l])return dp[u][l];
vis[u][l] = true;
if(!l) return dp[u][l] = 1;
dp[u][l] = 0;
for(int i = 0;i <sigma;i++){
if(ac.val[ac.ch[u][i]])continue;
if(p[i] == 0)continue;
dp[u][l] += p[i] * dfs(ac.ch[u][i],l-1);
}
return dp[u][l];
}
char sub[25];
int main(){
int t;
scanf("%d",&t);
int n;
int cas = 0;
while(t--){
memset(p,0,sizeof(p));
memset(dp,0,sizeof(dp));
memset(vis,0,sizeof(vis));
ac.clear();
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%s",sub);
ac.insert(sub,1);
}
ac.build();
scanf("%d",&n);
while (n--){
scanf("%s", sub);
scanf("%lf", &p[ac.idx(sub[0])]);
}
int L;
scanf("%d", &L);
printf("Case #%d: %.6f\n", ++cas, dfs(0, L));
}
}