Simple dictionary tree application, in the achievement of the time to judge on the line.
syntax to be aware of:
When using malloc and free to handle dynamic memory, only the memory of the object is freed, and the destructor of the object is not called, and the destructor of the object can be called while the memory of the object is freed by using new and delete. So it's more convenient to use new when building trie.
Note that it is important to release dynamic memory after each set of data is processed (it is essential to release dynamic memory at the appropriate time), otherwise it will cause a memory leak (resulting in mle after submission). Also note that there is such a knowledge point:
Delete and free only release the memory that the pointer points to, and do not kill the pointer itself. After both the free and delete, the pointer to clean memory needs to be set to NULL, that is p=null, otherwise the pointer to the memory space is released, but the value of the pointer p is the address of the record, the address of the memory is garbage, p is a "wild pointer." It also makes people think that P is a legitimate pointer, and if the program is longer, we usually check the p! before using a pointer =null, this will not work. At this point, if you release the space that P points to, the compiler will give an error because it is illegal to release a space that has been freed. It is not problematic to set it to null and then re-release it because the delete one 0 pointer is safe.
#include <iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<cmath>#include<map>#include<Set>#include<vector>#include<algorithm>#include<stack>#include<queue>#include<cctype>#include<sstream>using namespacestd;#definePII pair<int,int>#defineLL Long Long intConst inteps=1e-8;Const intinf=1000000000;Const intmaxn=10000+Ten;intT,n;Charss[ the];structtrie{trie*next[Ten]; intv; Trie () { for(intI=0; i<Ten; i++) {Next[i]=NULL; } v=0; }};trie*Root;BOOLBuildChar*s) { intlen=strlen (s); Trie*p=root,*Q; for(intI=0; i<len; i++) { intid=s[i]-'0'; if(p->next[id]==NULL) {Q=Newtrie; P->next[id]=Q; P=p->Next[id]; P->v=1; } Else if(p->next[id]->v==-1) { return false; } Else{p=p->Next[id]; P->v++; } } if(p->v>1)return false; Else{p->v=-1; return true; }}voidFang (trie*R) { if(R==null)return; Else { for(intI=0; i<Ten; i++) { if(r->Next[i]) Fang (R-Next[i]); }} delete r; R=NULL; return;}intMain () {//freopen ("In8.txt", "R", stdin);scanf"%d",&T); while(t--) {root=Newtrie; scanf ("%d",&N); BOOLans=true; for(intI=0; i<n; i++) {scanf ("%s", SS); if(ans==true) {ans=build (ss); } } if(ANS) puts ("YES"); ElsePuts"NO"); Fang (root); } return 0;}
HDU 1671 Phone List (trie tree)