UVALive 3942 Remember the Word(字典树 + 简单dp)

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1943

题意:给定文本串txt和n个模式串str,问有多少种方法用模式串中的任意几个拼成文本串(可重复用),最后结果模20071027。

思路:利用数组d[i]表示从文本串位置i到文本串末尾可用模式串中的任意几个拼成的种数。这样最后只需要输出d[0]即可。如果直接记忆化搜索的话,肯定会TLE。所以可以考虑对模式串建一棵字典树,每次求d[s]的时候,从txt[s]这个位置从字典树开始搜索,如果当前所在的结点为某个模式串的结点时,d[s] += d[i + 1]。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <stack>

using namespace std;

#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define ceil(x, y) (((x) + (y) - 1) / (y))

const int SIZE = 30;
const int N = 4e5 + 10;
const int M = 3e5 + 10;
const int INF = 0x7f7f7f7f;
const int MAX_WORD = 1e2 + 10;
const double EPS = 1e-9;
const int MOD = 20071027;

int sz, lens, lent;
int ch[N][SIZE];
bool ed[N];
long long d[M];
char txt[M];
char str[MAX_WORD];

int newnode() {
    memset(ch[sz], 0, sizeof(ch[sz]));
    ed[sz] = false;
    return sz++;
}

void init() {
    memset(d, 0, sizeof(d));
    sz = 0;
    newnode();
}

void insert() {
    int u = 0;
    for (int i = 0; i < lens; i++) {
        int v = str[i] - 'a';
        if (!ch[u][v])
            ch[u][v] = newnode();
        u = ch[u][v];
    }
    ed[u] = true;
}

void find(int s) {
    int u = 0;
    for (int i = s; i < lent; i++) {
        int v = txt[i] - 'a';
        if (!ch[u][v])
            return ;
        u = ch[u][v];
        if (ed[u])//如果为某个模式串结尾
            d[s] = (d[i + 1] + d[s]) % MOD;
    }
    if (ed[u])//如果该模式串本身到文本串结尾,则+1
        d[s]++;
}

int main() {    
    int i_case = 1;
    while (scanf("%s", txt) != EOF) {
        lent = strlen(txt);
        int n;
        scanf("%d", &n);
        init();
        for (int i = 0; i < n; i++) {
            scanf("%s", str);
            lens = strlen(str);
            insert();
        }
        for (int i = lent - 1; i >= 0; i--)//逆序
            find(i);

        printf("Case %d: %lld\n", i_case++, d[0]);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值