首页 > 代码库 > 字典树模板!

字典树模板!

 1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4  5 using namespace std; 6  7 struct tree 8 { 9     int count;10     tree *next[26];11 };12 tree *head;13 14 void Insert(char *ch)15 {16     int pp=0;17     tree *p;18     p=head;19     for(;;)20     {21         if(ch[pp]==\0) break;22         if(p->next[ch[pp]-a]!=NULL)23         {24             p=p->next[ch[pp]-a];25             p->count++;26         }27         else28         {29             tree *Q=(tree *)malloc(sizeof(tree));30             Q->count=1;31             for(int i=0;i<26;i++)32             {33                 Q->next[i]=NULL;34             }35             p->next[ch[pp]-a]=Q;36             p=Q;37         }38         pp++;39     }40 }41 42 int find(char *ch)43 {44     tree *p=head;45     int pp=0;46     for(;;)47     {48         if(ch[pp]==\0) return p->count;49         if(p->next[ch[pp]-a]==NULL) return 0;50         p=p->next[ch[pp]-a];51         pp++;52     }53     return 0;54 }55 int main()56 {57    // freopen("ACM.txt","r",stdin);58     head=(tree *)malloc(sizeof(tree));59     for(int i=0;i<26;i++)60         head->next[i]=NULL;61     //char a[12],b[12];62     //while(gets(a)&&a[0]!=‘\0‘)63     //{64     //    Insert(a);65     //}66     //while(scanf("%s",b)!=EOF)67     //{68     //   cout<<find(b)<<endl;69     //}70 71     return 0;72 }
View Code

 

字典树模板!