Time Limit:3000MS | Memory Limit:Unknown | 64bit IO Format: %lld & %llu |
Description
Neal is very curious about combinatorial problems, and now here comes a problem about words. Knowing 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 , 1S4000 .
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.
Sample Input
abcd 4 a b cd ab
Sample Output
Case 1: 2
题意:给出一个由S个不同单词组成的字典和一个长字符串。把这个字符串分解成若干个单词的连接(单词可重复使用),有多少种方法?
解题思路:用Trie存入字典,设dp[i]为从字符i开始的字符串的分解方案数,
则有dp[i] = sum{dp[i+len(x)] | 单词x为S[i...L]的前缀}。
#include<cstdio>
#include<cstring>
using namespace std;
const int mode = 20071027;
const int maxn = 310000;
char str[maxn];
int dp[maxn];
char a[110];
struct node{
int next[26];
int f;
}T[4000*100];
int tot;
void insert(){
int root=0;
for(int i=0;a[i];i++){
if(T[root].next[ a[i]-'a']==-1){
T[root].next[ a[i]-'a' ] = tot++;
}
root=T[root].next[a[i]-'a' ];
}
T[root].f=1;
}
int main(){
int n; int ca=1;
while(scanf("%s",str+1)!=EOF){
scanf("%d",&n);
memset(T,-1,sizeof(T)); tot=1;
while(n--){
scanf("%s",a);
insert();
}
memset(dp,0,sizeof(dp));
int len=strlen(str+1);
dp[0]=1; str[0]=1;
for(int i=0;str[i];i++){
int root=0;
for(int j=1;str[i+j];j++){
root=T[root].next[ str[i+j]-'a' ];
if(root==-1 ) break;
else{
if(T[root].f==1){
dp[i+j]+=dp[i];
while(dp[i+j]>mode)dp[i+j]-=mode;
}
}
}
}
printf("Case %d: %d\n",ca++,dp[len]);
}
return 0;
}