Time limit: 3.000 seconds
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 , 1S
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.
Sample Input
abcd 4 a b cd ab
Sample Output
Case 1: 2
给出n个单词和一个长串S,问这n个单词有多少种方法构成长串S。单词可以重复用。
思路:d[i]:用字典树中单词构成从i到L-1的字符串有多少种可能的组成方法。将字符串S从后往前看,d[L]=1。如果在字典树中查找到了长度为len的单词(以当前后缀中的前缀匹配字典树中的单词),d[i]+=d[i+len]。
d[i]不能表示从0到i-1的字符串有多少种可能组成方法,因为字典树只能是前缀与字典树单词的匹配。
#include<bits/stdc++.h>
using namespace std;
const int maxnode=4000*100+100;
const int sigma_size=26;
struct Trie
{
int ch[maxnode][sigma_size];
int val[maxnode];
int sz;
void Clear()
{
sz=1;
memset(ch,0,sizeof(ch));
}
int idx(char c)
{
return c-'a';
}
void Insert(char *s)
{
int u=0,n=strlen(s);
for(int i=0;i<n;i++)
{
int id=idx(s[i]);
if(ch[u][id]==0)
{
ch[u][id]=sz;
memset(ch[sz],0,sizeof(ch[sz]));
val[sz++]=0;
}
u=ch[u][id];
}
val[u]=n;
}
void Find(char *s,int len,vector<int> &vc)
{
int u=0;
for(int i=0;i<len;i++)
{
int id=idx(s[i]);
if(ch[u][id]==0)
return;
u=ch[u][id];
if(val[u]) vc.push_back(val[u]);
}
}
}trie;
const int MAXN=300000+1000;
const int MOD=20071027;
int d[MAXN];//d[i]:用字典树中单词构成从i到L-1的字符串有多少种可能的组成方法。
char S[MAXN],word[1000];
int main()
{
int kase=1;
while(scanf("%s",S)==1)
{
int w;
scanf("%d",&w);
trie.Clear();
for(int i=0;i<w;i++)
{
scanf("%s",word);
trie.Insert(word);
}
memset(d,0,sizeof(d));
int L=strlen(S);
d[L]=1;
for(int i=L-1;i>=0;i--)
{
vector<int> vc;
trie.Find(S+i,L-i,vc);
for(int j=0;j<vc.size();j++)
d[i]=(d[i]+d[i+vc[j]])%MOD;
}
printf("Case %d: %d\n", kase++, d[0]);
}
return 0;
}