首页 > 代码库 > UVA-1401-Remember the Word(Trie)
UVA-1401-Remember the Word(Trie)
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[i]表示从第i个字符开始到字符串尾的组合情况的方案数,从后往前推即可。
#include <stdio.h> #include <string.h> int son[400001][26],val[400001],dp[400001],cnt; char s[300001],ts[101]; void insert(char *str) { int u=0,i,j,id; for(i=0;str[i];i++) { id=str[i]-‘a‘; if(!son[u][id]) { for(j=0;j<26;j++) son[cnt][j]=0; val[cnt]=0; son[u][id]=cnt++; } u=son[u][id]; } val[u]++; } int main() { int n,i,j,u,id,casenum=1; while(~scanf("%s",s)) { for(i=0;i<26;i++) son[0][i]=0; cnt=1; scanf("%d",&n); while(n--) { scanf("%s",ts); insert(ts); } n=strlen(s); dp[n]=1; for(i=n-1;i>=0;i--) { u=0; j=i; id=s[j]-‘a‘; dp[i]=0; while(u=son[u][id])//如果可以继续走下去就继续走 { dp[i]+=val[u]%20071027*dp[j+1]%20071027; j++; if(j<n) id=s[j]-‘a‘; else break; } } printf("Case %d: %d\n",casenum++,dp[0]%20071027); } }