Record the number of times the Val array is logged with additional information.
Ps:trie Tree also has a dynamic notation, using pointers and dynamic allocation of memory instead of a continuous ch array, more memory savings.
reference:http://blog.csdn.net/architect19/article/details/8966247
1#include <cstdio>2#include <cstring>3#include <iostream>4 using namespacestd;5 #defineMaxnode 4000106 #defineSigma_size 227 8 CharA[maxnode][sigma_size];9 intT[maxnode];Ten intn,m; One //struct Trie A //{ - intCh[maxnode][sigma_size];//Ch[i][j]: Record node I of the child with the number J - intVal[maxnode];//additional information for the VAL[I]:I node, the //If val[i]=0 is not yet at the end of the word. Otherwise val[i] is the number of occurrences of the word - intsz; - voidTrie () - { +sz=1; -memset (CH,0,sizeof(CH)); +Memset (Val,0,sizeof(Val)); Amemset (T,0,sizeof(t)); at } - intIdxCharC//idx (c) is the number of the character C. - { - //A G C T - if(c=='A')return 1; - if(c=='G')return 2; in if(c=='C')return 3; - if(c=='T')return 4; to //return C ' A '; //The first character is a + } - voidInsert (CharS[sigma_size],intv) the { * intu=0, n=strlen (s); $ for(intI=0; i<n;i++)Panax Notoginseng { - intC=idx (s[i]); the if(!Ch[u][c]) + { Amemset (Ch[sz],0,sizeof(Ch[sz])); theval[sz]=0; +ch[u][c]=sz++; - } $u=Ch[u][c]; $ } - //Val[u]=v; -val[u]+=v; the } - intQuery (CharS[sigma_size])//Times of sWuyi { the intu=0, C; - inttm=strlen (s); Wu for(intI=0; i<tm;i++) - { About //c=s[i]-' A '; $C=idx (s[i]); - if(!ch[u][c])return 0; -u=Ch[u][c]; - //if (val[u]==1) return true; //if S is not finished yet, but the trie tree has reached the end, that is, the word on the tree is the prefix of S. A } + returnVal[u]; the } - //}; $ the intMain () the { the //freopen ("In.txt", "R", stdin); the //Ios::sync_with_stdio (false); - in //While (cin>>n>>m) the while(~SCANF ("%d%d",&n,&m)) the { About Trie (); the if((n!=0) && (m!=0)) the { the for(intI=1; i<=n;i++) + { - //cin>>a[i]; thescanf"%s", A[i]);BayiInsert (A[i],1); the } the for(intI=1; i<=n;i++) - { - inttm=Query (A[i]); thet[tm]++; the } the for(intI=1; i<=n;i++) theprintf"%d\n", t[i]/i); - //cout<<endl; the } the Else Break; the }94 the return 0; the}
Poj 2945 trie Tree Statistics string occurrences