[Trie树][dp] LA3942 Remember the Word 真·解法

31 篇文章 0 订阅
11 篇文章 0 订阅

上一篇的解法中,我们使用Trie树优化的dp,复杂度达到 3e9 ,限时3s,奇迹般地跑了2.929sAC了。然鹅。。。这并不是使用Trie的正确姿势。
Trie树是从根节点向下查找,如果我们计算的顺序和它一致,会大大降低复杂度。
重新定义 dpi 为字符串 s 的后缀i(即 sislen )的拆分方法。
则,

dpi=s[i,j]Triedpj+1

这样对于 dpi j 可以按从i len 的顺序,在Trie中便可逐层向下查找,时间复杂度下降到 O(nl) ,这次0.072s就过啦~~~

#include<bits/stdc++.h>
typedef long long LL;
typedef unsigned long long ull;
using namespace std;
const int maxn = 3e5+5;
const int maxn2 = 400000+8;
const int maxm = 26;
const int maxn3 = 105;
const int M = 20071027;
char s[maxn], s2[maxn3];
struct Trie
{
    int ch[maxn2][maxm];
    bitset<maxn2> val;
    int tot = 1;
    void init()
    {
        memset(ch[0], 0, sizeof ch[0]);
        val.reset();
        tot = 1;
    }
    void add(char *s)
    {
        int n = strlen(s);
        int cur = 0, id;
        for(int i = 0; i < n; ++i)
        {
            id = s[i] - 'a';
            if(!ch[cur][id])
            {
                memset(ch[tot], 0, sizeof ch[tot]);
                ch[cur][id] = tot++;
            }
            cur = ch[cur][id];
        }
        val[cur] = 1;
    }
    bool finda(char *s)
    {
        int n = strlen(s);
        int cur = 0, id;
        for(int i = 0; i < n; ++i)
        {
            id = s[i] - 'a';
            if(!ch[cur][id]) return false;
            cur = ch[cur][id];
        }
        return val.test(cur);
    }
}tr;
LL dp[maxn];
int main()
{
    int Case = 1;
    while(~scanf("%s", s+1))
    {
        int n;
        cin >> n;
        int len = strlen(s+1);
        tr.init();
        for(int i = 0; i < n; ++i)
        {
            scanf("%s", s2);
            tr.add(s2);
        }
        memset(dp, 0, sizeof dp);
        dp[len + 1] = 1;
        for(int i = len; i >= 1; --i)
        {
            int cur = 0, id;
            for(int j = i; j <= len; ++j)
            {
                id = s[j] - 'a';
                if(!tr.ch[cur][id]) break;
                cur = tr.ch[cur][id];
                if(tr.val[cur]) dp[i] = (dp[i] + dp[j+1])%M;
            }
        }
        printf("Case %d: ", Case++);
        cout << dp[1] << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值