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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章