UVA 1401 Remember the Word

字典树优化DP

                               Remember the Word
Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

[Submit]   [Go Back]   [Status]

Description

UVA 1401  Remember the Word
 

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<tex2html_verbatim_mark> , 1UVA 1401  Remember the WordSUVA 1401  Remember the Word4000<tex2html_verbatim_mark> .

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.

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
 #include <iostream>
#include <cstdio>
#include <cstring>
#include <string> using namespace std; const int MOD=;
const int maxn=; int m,dp[];
char str[]; struct Trie
{
int tot,root,child[maxn][];
bool flag[maxn];
Trie()
{
memset(child[],,sizeof(child[]));
flag[]=false;
root=tot=;
}
void Init()
{
memset(child[],,sizeof(child[]));
flag[]=false;
root=tot=;
}
void Insert(const char*str)
{
int *cur=&root;
for(const char *p=str;*p;p++)
{
cur=&child[*cur][*p-'a'];
if(*cur==)
{
*cur=++tot;
memset(child[tot],,sizeof(child[tot]));
flag[tot]=false;
}
}
flag[*cur]=true;
}
bool query(const char* str,int i)
{
int *cur=&root;
int l=;
for(const char*p=str;*p&&*cur;p++,l++)
{
cur=&child[*cur][*p-'a'];
if(flag[*cur])
{
dp[i]=(dp[i]+dp[i+l])%MOD;
}
}
return (*cur&&flag[*cur]);
}
}tree; int main()
{
int cas=;
while(scanf("%s",str)!=EOF)
{
int len=strlen(str);
scanf("%d",&m);
tree.Init();
while(m--)
{
char dic[];
scanf("%s",dic);
tree.Insert(dic);
}
memset(dp,,sizeof(dp));
dp[len]=;
for(int i=len-;i>=;i--)
{
tree.query(str+i,i);
}
printf("Case %d: %d\n",cas++,dp[]%MOD);
}
return ;
}
上一篇:activemq p2p方式


下一篇:【BZOJ】1012: [JSOI2008]最大数maxnumber 树状数组求区间最值