source code: #include<iostream>using namespacestd;strings;intN,num (0);structtreetype{CharT//used for node-stored characters. BOOLOver//used to mark whether the end of this string. intNext,deep,same;//used to mark the next layer node, the number of layers, and the next sibling node for this node, respectively. }tree[100001];voidX1 (stringS//Insert. { intM=s.size ()-1K0);//Note that in C + +, the string exists in the form of a character array beginning with 0. while(1) { if(tree[k].deep==m)//this string is inserted. {tree[k].over=true; Break; } if(tree[k].next==-1)//This node has no sons. {num++;//used to increase the node number. tree[num].deep=tree[k].deep+1; TREE[NUM].T=S[tree[num].deep]; Tree[num].over=false; Tree[num].same=-1;//Initialize brother. tree[num].next=-1;//Initialize the son. Tree[k].next=num;//mark the son. K=num;//number overlay. } Else //This node has a son. {k=tree[k].next;//Be careful not to worry about your father. while(tree[k].t!=s[tree[k].deep]&&tree[k].same!=-1) K=tree[k].same;//match the brothers in turn. if(tree[k].t!=S[tree[k].deep]) {num++;//In the same vein, the half matches the same level. tree[num].deep=Tree[k].deep; TREE[NUM].T=S[tree[num].deep]; Tree[num].over=false; Tree[num].same=-1; Tree[num].next=-1; Tree[k].same=num;//Mark Brother. k=num; } } }}BOOLX2 (stringS//find. { intM=s.size ()-1K0); while(1) { if(Tree[k].deep==m&&tree[k].over)//the match was successful. return true; if(tree[k].next==-1)//no next layer but did not exit, so the match is unsuccessful. return false; K=tree[k].next;//Be careful not to worry about your father. while(tree[k].t!=s[tree[k].deep]&&tree[k].same!=-1) K=tree[k].same;//make a sibling match. if(Tree[k].t!=s[tree[k].deep])//brother did not match successfully. return false; }}intMain () {tree[0].deep=0;//initializes the root node. tree[0].over=false; tree[0].next=-1; tree[0].same=-1; CIN>>N; for(intA=1; a<=n;a++) { intT; CIN>>T; CIN>>s;//it does not seem to be possible to use Getline (). s=" "+s;//Note that in C + +, the string exists in the form of a character array beginning with 0. if(t==1) x1 (s); if(t==2) if(x2 (s)) printf ("yes\n"); Elseprintf ("no\n"); } return 0;}
Data structure--dictionary tree (c + +)