华电北风吹
日期:2016-04-02
Trie树,又名前缀树。Trie树的存储结构与B树类似。需要注意的一点是Trie树的节点不保存任何信息,所有的信息都保存在边上。Trie树比较简单,直接上代码吧。
struct TrieNode
{
int count;
TrieNode* next[26];
bool exist;
TrieNode() :count(0), exist(false);
};
void Insert(TrieNode* root, string word)
{
TrieNode* node = root;
for (int i = 0; i < word.length(); i++)
{
int id = word[i] - 'a';
if (node->next[id] == NULL)
{
node->next[id] = new TrieNode();
}
node = node->next[id];
node->count += 1;
}
node->exist = true;
}
int Search(TrieNode* root, string word)
{
TrieNode* node = root;
for (int i = 0; i < word.length(); i++)
{
int id = word[i] - 'a';
node = node->next[id];
if (node == NULL)
return 0;
}
return node->count;
}
int main(void)
{
TrieNode* root = new TrieNode();
int n;
string s;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> s;
Insert(root, s);
}
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> s;
cout << Search(root, s) << endl;
}
return 0;
}