Basic implementation of the trie tree
The insert, delete, and find operations of the letter tree are simple. Use a repeat loop, that is, find the child tree corresponding to the first letter in the I cycle, and then perform the corresponding operation. To implement this letter tree, we can save it with the most common array (static open memory). Of course, we can also open dynamic pointer types (Dynamic Open memory ). There are three methods for pointing a node to a son:
1. Open a small array of letters for each node. The corresponding subscript is the letter represented by the Son, and the content is the position of the son corresponding to the big array, that is, the label;
2. Create a linked list for each node and record who each son is in a certain order;
3. Use the expression of the Left son and right brother to record the tree.
The three methods have their own characteristics. The first method is easy to implement, but the actual space requirements are large; the second method is easy to implement, the space requirements are relatively small, but time-consuming; the third method is the minimum space requirement, but it is relatively time-consuming and not easy to write.
Here we use the first method, which is fast and suitable for ACM competitions.
The size of the Child array is customized. The default value is 26 letters;
# Include <cstdio> # include <cstring> # include <cstdlib> # include <algorithm> # include <cmath> using namespace STD; typestrudef CT trie {int ncount; // The number of times the node prefix appears, struct trie * Next [26]; // child node} trie; trie memory [1000000]; // first allocate memory malloc expense time int allocp = 0; // initialize the node. Ncount is counted as 1, and next is all nulltrie * initnode () {trie * TMP = & memory [allocp ++]; TMP-> ncount = 1; for (INT I = 0; I <26; I ++) TMP-> next [I] = NULL; return TMP;} void inserttrie (trie ** proot, char * Str) {trie * TMP = * proot; int I = 0, K; // insert while (STR [I]) {k = STR [I]-'A' one by one '; if (TMP-> next [k]) {TMP-> next [k]-> ncount ++;} else {TMP-> next [k] = initnode ();} TMP = TMP-> next [k]; I ++ ;}} int searchtrie (trie * root, char * Str) {If (root = NULL) return 0; trie * TMP = root; int I = 0, K; while (STR [I]) {k = STR [I]-'A '; if (TMP-> next [k]) {TMP = TMP-> next [k];} else {return 0;} I ++;} return TMP-> ncount; // return the ncount} int main () {int M, N; char s [11]; trie * root = initnode () saved at the last node (); scanf ("% d", & N); For (INT I = 0; I <n; I ++) {scanf ("% s", S ); inserttrie (& root, S) ;}scanf ("% d", & M); For (INT I = 0; I <m; I ++) {scanf ("% s", S); printf ("% d \ n", searchtrie (root, S);} return 0 ;}
Trie tree (Dictionary tree) Personal Template