码迷,mamicode.com
首页 > 其他好文 > 详细

hihocoder(1014) Trie树

时间:2015-04-11 08:55:08      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Trie树又称单词查找树,多应用与搜索引擎或者输入法的词频统计,利用字符串的公共前缀加快查找速度。

第一次接触,不过代码还是比较好写的。

Impl:

技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 
 5 struct TrieTree
 6 {
 7     int count;
 8     TrieTree* word[26];
 9     TrieTree()
10     {   
11         count = 0;
12         for (int i = 0; i < 26; ++i) word[i] = NULL;
13     }   
14 };
15 
16 void buildTrie(const char* word, TrieTree* trieTree)
17 {
18     int i = 0;
19     while (word[i] != \0)
20     {   
21         int index = word[i] - a;
22         if (!trieTree->word[index])
23             trieTree->word[index] = new TrieTree();
24         trieTree = trieTree->word[index];
25         trieTree->count++;
26         i++;
27     }   
28 }
29 
30 int queryTrie(const char* word, TrieTree* trieTree)
31 {
32     int i = 0;
33     while (word[i] != \0 && trieTree)
34     {   
35         trieTree = trieTree->word[word[i] - a];
36         i++;
37     }   
38     if(!trieTree) return 0;
39     else return trieTree->count;
40 }
41 
42 char word[20];
43 int main()
44 {
45     int n;
46     scanf("%d", &n);
47     TrieTree* root = new TrieTree();
48     while (n--)
49     {
50         scanf("%s", word);
51         buildTrie(word, root);
52     }
53 
54     scanf("%d", &n);
55     while (n--)
56     {
57         scanf("%s", word);
58         printf("%d\n",queryTrie(word, root));
59     }
60 
61     return 0;
62 }
View Code

 

hihocoder(1014) Trie树

标签:

原文地址:http://www.cnblogs.com/sheepsheep/p/4416177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!