1, to a string, in a set of words, to use the word set to form a string, a total number of groups of methods.
Example: string ABCD, Word set A, B, CD, AB
Combination method: 2 kinds:
A,b,cd
Ab,cd
2. Set up a dictionary tree for the word set and then forward Dp,dp[i]=dp[i]+dp[i+len (x) from the back; where x is the prefix length that is currently found.
3.
#include <iostream>#include<stdio.h>#include<string.h>using namespacestd;#defineMAX 26#defineMOD 20071027intdp[300005];structtrie{Trie*Next[max]; intV//as needed, 1 means no such word, 1 means there is this word}; Trie*Root;voidCreatetrie (Char*str) { intLen =strlen (str); Trie*p = root, *P; for(intI=0; i<len; ++i) {intid = str[i]-'a'; if(P->next[id] = =NULL) { //q = (Trie *) malloc (sizeof (Trie));Q =NewTrie; Q->v =1;//Initial v==1 for(intj=0; j<max; ++j) Q->NEXT[J] =NULL; P->next[id] =Q; } P= p->Next[id]; } P->v =-1;//if at the end, change V to 1 to indicate}intFindtrie (Char*STR,intMI,intLen) { intret=0; //int len = strlen (str);//It's a waste of time to calculate every time.Trie *p =Root; for(intI=mi; i<len; ++i) {intid = str[i]-'a'; P= p->Next[id]; if(p = = NULL)//if it is an empty set, the string that is prefixed by this is not saved returnret; if(P->v = =-1){//a string already in the character set is the prefix of this stringRet= (ret+dp[i+1])%MOD; } } returnret;}intDeletetrie (trie*T) { inti; if(t==NULL)return 0; for(i=0; i<max; i++) { if(t->next[i]!=NULL) Deletetrie (T-Next[i]); } //Free (T); Delete(T); return 0;}intMain () {Charstr[300005]; Charstr2[ the]; intI,s,len,mcase=0; while(~SCANF ("%s", str)) {Root=NewTrie; for(i=0; i<max; i++) Root->next[i]=NULL; Memset (DP,0,sizeof(DP)); Len=strlen (str); scanf ("%d",&S); while(s--) {scanf ("%s", STR2); Createtrie (STR2); } Dp[len]=1; for(i=len-1; i>=0;--i) dp[i]=Findtrie (Str,i,len); printf ("Case %d:%d\n", ++mcase,dp[0]); Delete(root); } return 0;}
View Code
UVA-1401 Remember the Word (TRIE+DP)