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
DP,设d[i]为从下标i开始的串的能分的种树,则d[i] = sum{d[i...L(w)] | W是所有以i下标字母开头的单词,L是W的长度};
这道题,提交了多遍,老是RE,最后差得结果是在递归中开了内存,当数据很大时,则内存溢出了。一定注意不要在递归中随便开新的内存,谨慎使用list, new.
还有一个问题,就是初始化,这是我敲代码常出错的地方。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <vector>
using namespace std;
const int MAX_LEN = 300000 + 10, MAX_SIZE = 4000 * 100 + 10,MAX_WORD = 100 + 5;
const int MAX_CHR = 26 + 4,MOD = 20071027;
char sq[MAX_LEN];
int chd[MAX_SIZE][MAX_CHR],val[MAX_SIZE],size,s;
int d[MAX_LEN];
int idx(char c)
{
return c - 'a';
}
void insert(char *s)
{
int cur = 0;
for(int i = 0; s[i]; ++i)
{
int c = idx(s[i]);
if(!chd[cur][c])
{
chd[cur][c] = size;
val[size] = 0;
cur = size;
size++;
}
else cur = chd[cur][c];
val[cur] = 1;
}
void get_words_len(char *s ,int &cur_len)
{
int cur = 0,pos = 0;
for(int i = 0; s[i]; ++i)
{
int c = idx(s[i]);
if(!chd[cur][c])break;
cur = chd[cur][c];
if(val[cur] && (i + 1) > cur_len)
{
cur_len = i + 1;
return;
}
}
cur_len = 0;
}
int calcu(char *str)
{
if(str[0] == 0)return 1;
int idx = str - sq;
if(d[idx]!= -1) return d[idx];
int words_len = 0;
while(1)
{
get_words_len(str, words_len);
if(!words_len)break;
int val;
val = calcu(str + words_len);
d[idx] = d[idx] == -1 ? val : d[idx] + val;
d[idx] %= MOD;
}
if(d[idx] == -1)d[idx] = 0;
return d[idx];
}
int main()
{
char word[MAX_WORD];
int cnt = 0;
while(scanf("%s",sq) != -1)
{
scanf("%d",&s);
size = 1;
memset(chd, 0, sizeof(chd[0]) * (s + 5) * 100);
memset(val, 0, sizeof(int) * (s + 5) * 100);
int len = strlen(sq);
for(int i = 0; i <= len; ++i)d[i] = -1;
while(s--)
{
scanf("%s",word);
insert(word);
}
printf("Case %d: %d\n",++cnt, calcu(sq));
}
return 0;
}