首页 > 代码库 > 《 字典树模板_递归 》

《 字典树模板_递归 》

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

《 字典树模板_递归 》