您的位置:首页 > 其它

Trie(字典树)

2016-04-12 15:45 357 查看
前两天看到hihoCoder上一道Trie树的题,正好学习一下新的数据结构和它的应用

题目链接: http://hihocoder.com/problemset/problem/1014

题目简介:输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。

样例输入:

5

babaab

babbbaaaa

abba

aaaaabaa

babaababb

5

babb

baabaaa

bab

bb

bbabbaab

样例输出:

1

0

3

0

0

自己编写的AC代码如下:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
#define MAX 26
struct Trie
{
int count;
Trie*child[MAX];
};

void Create(Trie *tree)
{
tree->count = 0;
for (int i = 0; i < MAX;i++)
{
tree->child[i] = NULL;
}
}

void Destroy(Trie *tree)
{
for (int i = 0; i < MAX; i++)
{
if (tree->child[i])
Destroy(tree->child[i]);
}
delete tree;
tree = NULL;
}

void Insert(Trie *head)
{
int n; string s;
Trie *tree = NULL;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> s;
int len = s.size();
tree = head;
for (int j = 0; j < len; j++)
{
int index = s[j] - 'a';
if (tree->child[index])
{
tree->child[index]->count++;
tree = tree->child[index];
}

else
{
tree->child[index] = new Trie();
tree = tree->child[index];
tree->count = 1;
for (int k = 0; k < MAX; k++)
{
tree->child[k] = NULL;
}
}
}
}
tree = NULL;
}

void Search(Trie *head)
{
int m; string s;
Trie *tree = NULL;
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> s;
int len = s.size();
tree = head;
int j;
for (j = 0; j < len; j++)
{
int index = s[j] - 'a';
if (tree->child[index])
tree = tree->child[index];
else
{
cout << 0 << endl;
break;
}
}
if (j==len)
cout << tree->count << endl;
}
}
int main()
{
Trie *head = new Trie();
Create(head);
Insert(head);
Search(head);
Destroy(head);
return 0;
}


PS:代码中的删除应该有点问题,只是程序中没有体现出来,连最简单的删除节点都忘了,囧,应该定义两个节点,一个前驱,一个当前,删除当前节点,前驱对应的指针置为NULL。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: