This question is mainly implemented in recursion.
Set a word W, which is composed of (w1, w2, ·, wn) letters to determine the combination of words.
Given any suffix (wi, wi + 1,..., wn), you must find its prefix to determine the number of combinations. Set the suffix (wi, wi + 1,..., wn) to x, find the number of prefixes in the suffix (the prefix here refers to the word ). Set d (I) to indicate the number of combination methods for the Suffix from I to n, set x to the prefix of the suffix, and the remaining part of the string is y. Then d (I) = d (len (x) + I ).
Why? A prefix corresponds to at least one combination, but the group prefix is not necessarily consistent. You need to determine whether y is a word. Therefore, you need to determine the number of combinations of d (len (x) + I. Because a suffix has multiple prefixes, We Need To sum all prefixes. There is a recursive relationship below:
D (I) = sum {d (len (x) + I )}
Therefore, you can use the Trie tree to quickly find the prefix.
The following code is used:
#include<stdio.h>#include<string.h>#define maxn 500010int ch[maxn][26];int val[maxn],cnt,n;int d[maxn];char str[maxn],s[110];void initi(){ cnt = 1; memset(ch[0],0,sizeof(ch[0])); memset(d,0,sizeof(d));}void insert_Trie(char *s){ int u = 0; while(*s) { int id = *s - 'a'; if(ch[u][id] == 0) { memset(ch[cnt],0,sizeof(ch[cnt])); val[cnt] = 0; ch[u][id] = cnt++; } u = ch[u][id]; s++; } val[u] = -1;}int main(){ int c = 0; while(scanf("%s",str) != EOF) { c++; initi(); scanf("%d",&n); for(int i = 0; i < n; i++) { scanf("%s",s); insert_Trie(s); } int len = strlen(str); d[len] = 1; for(int i = len-1; i >= 0; i--) { int j,k; int u = 0; for(j = 0,k = i; k < len; j++,k++) { int id = str[k] - 'a'; if(!ch[u][id]) break; else if(val[ch[u][id]] == -1) { d[i] += d[i+j+1]; if(d[i] >= 20071027) d[i] %= 20071027; } u = ch[u][id]; } } printf("Case %d: ",c); printf("%d\n",d[0]%20071027); } return 0;}
Note:
1. query operations are not required when prefix search is performed.
2. The result is very large, and int will pop up. You need to handle it because it is mod.