uva11468 Substring

5 篇文章 0 订阅
2 篇文章 0 订阅

题面在这里

题意:

给一些模式串。
再给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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值