UVALive - 3942 Remember the Word[Trie DP]

UVALive - 3942

Neal is very curious about combinatorial problems, and now here comes a problem about words. Know- ing that Ray has a photographic memory and this may not trouble him, Neal gives it to Jiejie.

Since Jiejie can’t remember numbers clearly, he just uses sticks to help himself. Allowing for Jiejie’s only 20071027 sticks, he can only record the remainders of the numbers divided by total amount of sticks.

The problem is as follows: a word needs to be divided into small pieces in such a way that each piece is from some given set of words. Given a word and the set of words, Jiejie should calculate the number of ways the given word can be divided, using the words in the set.

Input

The input file contains multiple test cases. For each test case: the first line contains the given word whose length is no more than 300 000.

The second line contains an integer S, 1 ≤ S ≤ 4000.

Each of the following S lines contains one word from the set. Each word will be at most 100 characters long. There will be no two identical words and all letters in the words will be lowercase.

There is a blank line between consecutive test cases. You should proceed to the end of file.

Output

For each test case, output the number, as described above, from the task description modulo 20071027.


白书,字符串用单词分割


DP,d[i]表示i到结尾的方案数

d[i]=sum{d[i+len(x)]|x是s[i]开始的前缀}

暴力的话枚举每个单词代价4000

可以用Trie找前缀代价100

//
// main.cpp
// la3942
//
// Created by Candy on 10/14/16.
// Copyright © 2016 Candy. All rights reserved.
// #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int W=3e5+,S=4e3+,N=,MOD=;
int n;
char s[W];
char a[S][N];
int t[S*N][],sz=,val[S*N];
void init(){
memset(t[],,sizeof(t[]));
}
void insert(char ch[]){
int len=strlen(ch+),u=;
for(int i=;i<=len;i++){
int c=ch[i]-'a';
if(!t[u][c]){
t[u][c]=++sz;
memset(t[sz],,sizeof(t[sz]));
val[sz]=;
}
u=t[u][c];
}
val[u]=;
}
int d[W];
void dp(){
memset(d,,sizeof(d));
int n=strlen(s+);
d[n+]=;
for(int i=n;i>=;i--){
int u=;
for(int j=i;j<=n&&j<=i+;j++){
int c=s[j]-'a';
if(!t[u][c]) break;
u=t[u][c];
if(val[u]) d[i]=(d[i]+d[j+])%MOD;
}
}
}
int main(int argc, const char * argv[]) {
int cas=;
while(scanf("%s%d",s+,&n)!=EOF){
init();
for(int i=;i<=n;i++){
scanf("%s",a[i]+);
insert(a[i]);
}
dp();
printf("Case %d: %d\n",++cas,d[]);
}
return ;
}
上一篇:什么是nrm


下一篇:UVALive - 3942 Remember the Word[树状数组]