Based on https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int amn=1e5+5; 4 int trie[amn][26],tid; 5 bool isw[amn]; 6 int sum[amn]; 7 void init(){ 8 memset(isw,0,sizeof isw); 9 memset(trie,0,sizeof trie); 10 memset(sum,0,sizeof sum); 11 tid=0 ; /// node number in the whole tree 12 is } 13 is void INSERT ( char * S) { /// inserting a word, if you want to query suffix reverse insertion 14 int len = strlen (S), RT = 0 ; 15 for ( int I = 0 ; I <len; I ++ ) { 16 int ID = S [I] - ' a ' ; /// see son select which of the current node . 17 IF ! ( Trie [RT] [ID] ) 18 is Trie [RT] [ID] = ++ TID; . 19 SUM [RT] ++; /// prefix statistics 20 = RT Trie [RT] [ID]; 21 is } 22 is ISW [RT] = . 1 ; /// end of the word mark 23 is } 24 BOOL isword ( char * S) { /// query whether there is the word 25 int len = strlen (S), RT = 0 ; 26 is for ( int I = 0 ; I <len; I ++ ) { 27 int ID = S [I] - ' A ' ; 28 IF (Trie [RT] [ID]!) return 0 ; 29 RT = Trie [RT] [ID]; 30 } 31 is return ISW [RT]; 32 } 33 is BOOL isprefix ( char * S) { /// Query the existence of this prefix 34 is int len = strlen (S), RT = 0 ; 35 for ( int I = 0 ; I <len; I ++ ) { 36 int ID = S [I] - ' A ' ; 37 [ IF ! (Trie [RT] [ID]) return 0 ; 38 is RT = Trie [RT] [ID]; 39 } 40 return . 1 ; 41 is } 42 is int prefix_sum ( char * S) { /// Query the current number of prefixes occurring 43 is int len = strlen (S), RT = 0 ; 44 is for ( int I = 0 ; I <len; I ++ ) { 45 int ID = S [I] - ' A ' ; 46 is IF (Trie [RT] [ID]!) return 0 ; 47 RT = Trie [RT] [ID]; 48 } 49 return SUM [RT]; 50 } 51 is int main () { 52 is init(); 53 char *s="hello",*s1="he"; 54 insert(s); 55 printf("isword:%d isprefix:%d prefix_sum:%d\n",isword(s),isprefix(s1),prefix_sum(s1)); 56 }