字典樹優化DPphp
Time Limit: 3000MS | Memory Limit: Unknown | 64bit IO Format: %lld & %llu |
[Submit] [Go Back] [Status] html
Descriptionios
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.ide
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.this
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.spa
The second line contains an integer S<tex2html_verbatim_mark> , 1S
4000<tex2html_verbatim_mark> .code
Each of the following S<tex2html_verbatim_mark> 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.orm
There is a blank line between consecutive test cases.htm
You should proceed to the end of file.
For each test case, output the number, as described above, from the task description modulo 20071027.
abcd 4 a b cd ab
Case 1: 2
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 6 using namespace std; 7 8 const int MOD=20071027; 9 const int maxn=400010; 10 11 int m,dp[400030]; 12 char str[400030]; 13 14 struct Trie 15 { 16 int tot,root,child[maxn][27]; 17 bool flag[maxn]; 18 Trie() 19 { 20 memset(child[1],0,sizeof(child[1])); 21 flag[1]=false; 22 root=tot=1; 23 } 24 void Init() 25 { 26 memset(child[1],0,sizeof(child[1])); 27 flag[1]=false; 28 root=tot=1; 29 } 30 void Insert(const char*str) 31 { 32 int *cur=&root; 33 for(const char *p=str;*p;p++) 34 { 35 cur=&child[*cur][*p-'a']; 36 if(*cur==0) 37 { 38 *cur=++tot; 39 memset(child[tot],0,sizeof(child[tot])); 40 flag[tot]=false; 41 } 42 } 43 flag[*cur]=true; 44 } 45 bool query(const char* str,int i) 46 { 47 int *cur=&root; 48 int l=1; 49 for(const char*p=str;*p&&*cur;p++,l++) 50 { 51 cur=&child[*cur][*p-'a']; 52 if(flag[*cur]) 53 { 54 dp[i]=(dp[i]+dp[i+l])%MOD; 55 } 56 } 57 return (*cur&&flag[*cur]); 58 } 59 }tree; 60 61 int main() 62 { 63 int cas=1; 64 while(scanf("%s",str)!=EOF) 65 { 66 int len=strlen(str); 67 scanf("%d",&m); 68 tree.Init(); 69 while(m--) 70 { 71 char dic[120]; 72 scanf("%s",dic); 73 tree.Insert(dic); 74 } 75 memset(dp,0,sizeof(dp)); 76 dp[len]=1; 77 for(int i=len-1;i>=0;i--) 78 { 79 tree.query(str+i,i); 80 } 81 printf("Case %d: %d\n",cas++,dp[0]%MOD); 82 } 83 return 0; 84 }