您的位置:首页 > 其它

【Trie树】 Hihocoder 1014

2017-05-08 18:07 411 查看
 题目链接:

点击打开链接

较基础的前缀树题目,每次插入新单词更新结点的计数即可。

使用指针实现。另外,可考虑用数组构建Trie树,用数组保存每个结点的所有子结点,用下标直接存取

参考代码:

#include <iostream>
#include <cstring>

using namespace std;

struct Trie
{
char ch;
int val;
Trie* next[26];

Trie(){
val = 0;
memset(next, NULL, sizeof(next));
}
};

void trieInsert(Trie* tree, char* word )
{
int len = 0;
char* tmp = word;
while(*tmp != '\0')
{
len ++;
tmp ++;
}

for(int i=0; i<len; i++)
{
int idx = word[i] - 'a';
if(tree->next[idx] == NULL)
tree->next[idx] = new Trie;

tree = tree->next[idx];
tree->val ++;
}

}

int trieSearch(Trie* tree, char* word)
{
for( ; *word!='\0'; word++)
{
int idx = *word - 'a';
if(tree->next[idx] == NULL)
return 0;
else
tree = tree->next[idx];
}

return tree->val;
}

int main()
{
int n=0, m=0;
Trie* tree = new Trie;

// freopen("in.txt", "r", stdin);

cin>>n;
for(int i=0; i<n; i++)
{
char word[12] = {'\0'};
cin>>word;
trieInsert(tree, word);
}

cin>>m;
for (int i=0; i<m; i++)
{
char word[12] = {'\0'};
cin>>word;
cout<<trieSearch(tree, word)<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息