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代码如下:
PS:代码中的删除应该有点问题,只是程序中没有体现出来,连最简单的删除节点都忘了,囧,应该定义两个节点,一个前驱,一个当前,删除当前节点,前驱对应的指针置为NULL。
题目链接: 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。
相关文章推荐
- ralink wifi 驱动 显示 调试信息
- hbase 常用操作语法
- css3属性选择器
- 虚与实:“有趣”比“秀肌肉”更聪明
- python面对对象编程----------7:callable(类调用)与context(上下文)
- 《超实用的Node.js代码段》连载三:Node.js深受欢迎的六大原因
- 详解Android应用中使用TabHost组件进行布局的基本方法
- leetcode 34. Search for a Range
- 键盘的Unicode码
- HDFS源码分析EditLog之读取操作符
- hive使用中遇到的问题2
- 数据库事务的隔离性介绍
- 在jquery中,遍历对象和数组,经常会用到$().each和$.each(),两个方法。两个方法是有区别的,从而这两个方法在针对不同的操作上,显示了各自的特点。 $().each,对于这个方法,在
- 棋子翻转
- [超级懒人最简单法]iPhone 6 plus 适配切图方法分享(转载文章)
- Vim命令合集
- 手动purge优化器的统计信息与AWR快照,减少对sysaux表空间的占用
- Hadoop: Setting up a Single Node Cluster
- 异常 org.jetbrains.android.uipreview.RenderingException android studio
- tomcat下jndi的三种配置方式