题意:给定文本串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;
}