首页 > 代码库 > hiho 第二周

hiho 第二周

Trie树,第一次写,简单的建树+搜索

它的思路hiho上讲得很清楚,good~

 

 1 #include<iostream> 2 #include<string> 3 using namespace std; 4 char word[11]; 5 int n,m; 6 struct trie 7 { 8     int num; 9     trie *next[26];10     trie()11     {12         num = 0;13         for(int i = 0; i < 26; i++)14             next[i] = 0;15     }16 }t;17 trie *p;18 void setup(char w[])19 {20     p = &t;21     for(int i = 0; word[i]; i++)22     {23         int pos = word[i] - a;24         if(p->next[pos] == 0)25         {26             trie *q;27             q = new trie();28             p->next[pos] = q;29         }30         p = p->next[pos];31         p->num++;32     }33 }34 35 int findnum(char word[])36 {37     p = &t;38     for(int i = 0; word[i];i++)39     {40         int pos = word[i] - a;41         if(p->next[pos] == 0) return 0;42         p = p->next[pos];43     }44     return p->num;45 }46 47 int main()48 {49     cin>>n;50     while(n--)51     {52         cin>>word;53         setup(word);54     }55     cin>>m;56     while(m--)57     {58         cin>>word;59         cout<<findnum(word)<<endl;60     }61     return 0;62 }