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
解决方案:递推公式为:d[i]=sum{d[i+len(x)]|x单词是S[i....L]前缀}。x可用字典树来查找,效率高了许多。
代码:#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<algorithm> #define MMAX 300003 #define maxn 400003 #define MOD 20071027 using namespace std; int S; char word[MMAX]; char str[103]; int len[4003],d[MMAX]; struct Trie { int ch[maxn][26]; int val[maxn]; int sz; void init() { sz=1;///为下一个节点更新做准备 memset(ch[0],0,sizeof(ch[0]));///初始时只有一个节点 memset(val,0,sizeof(val)); } int idx(char c) { return c-'a'; }///字符与数字的转化 void Insert(char *s,int v){///V为非0,且标记节点 int len=strlen(s); int u=0;///从第一个节点开始 for(int i=0;i<len;i++){ int c=idx(s[i]); if(!ch[u][c]){ memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0; ch[u][c]=sz++; } u=ch[u][c]; } val[u]=v;///最后一个字符为标记v }///插入一个字符串 void query(char *s,int len,vector <int > &ans){ int u=0;///从第一个节点开始 for(int i=0;i<len;i++){ int c=idx(s[i]); if(!ch[u][c]){ break; } u=ch[u][c]; if(val[u]!=0) ans.push_back(val[u]); } } }T; int main() { int k=0; while(~scanf("%s",word)){ T.init(); scanf("%d",&S); for(int i=0;i<S;i++){ scanf("%s",str); T.Insert(str,i+1); len[i+1]=strlen(str); } int L=strlen(word); memset(d,0,sizeof(d)); d[L]=1; for(int i=L-1;i>=0;i--){ vector<int >S; T.query(word+i,L-i,S); for(int j=0;j<S.size();j++){ d[i]=(d[i]+d[i+len[S[j]]])%MOD;///由递推公式写出的代码,自右向左推。 } } printf("Case %d: ",++k); printf("%d\n",d[0]); } return 0; }