UVa 1401 - Remember the Word
出處:https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=4147
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, 1 ≤ S ≤ 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
解題策略:建立trie,使用dp方式計算可能性
dp[i],表示目標字串str[0]到str[i-1]的組成個數
(1)dp初始化
若str[0]是組成字串,則dp[0]=1;若str[0]到str[1]是組成字串,則dp[1]=1,以此類推;若str[0]到str[len-1]是組成字串,則dp[len-1]=1
(2)dp規則
當dp[i-1]>0時,表示str[0..i-1]是有可能組成的字串,且如果str[i]到str[i+j-1]是輸入字串,則dp[j] = dp[j]+dp[i-1]
(3)使用巢狀迴圈找出str[i..j]的每個子字串是否存在,使用dp規則進行更新,過程中如果遇到NULL就停止,加快速度