【hihocoder】1014. Trie树
2015-09-25 16:31
363 查看
Trie树的建立,基本上就是按照深度优先搜索的顺序来进行插入结点。
同时,设定一个label,来记录当前经过该node时有多少结点,便于在
查询的时候,可以直接输出,而不需要再次dfs进行搜索。
同时,设定一个label,来记录当前经过该node时有多少结点,便于在
查询的时候,可以直接输出,而不需要再次dfs进行搜索。
/** * @author johnsondu * @time 16:24 9th Sep 2015 * @type trie tree * @url http://hihocoder.com/problemset/problem/1014 */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <string> #include <algorithm> #include <map> #include <vector> using namespace std; const int MAXN = 105; struct Trie { char ch; int cnt; Trie *next[26]; Trie() { cnt = 0; for(int i = 0; i < 26; i ++) next[i] = NULL; } }; Trie root; int ans; void insertWord(char* str) { int len = strlen(str); Trie *head = &root; for(int i = 0; i < len; i ++) { int idx = str[i] - 'a'; if(head->next[idx] == NULL) { Trie *node = new Trie; node->ch = str[i]; head->next[idx] = node; } head = head->next[idx]; head->cnt ++; } } void queryWord(char *str) { Trie* head = &root; int len = strlen(str); ans = 0; for(int i = 0; i < len; i ++) { int idx = str[i] - 'a'; if(head->next[idx] == NULL) return; else { head = head->next[idx]; } } ans = head->cnt; } int main() { char str[MAXN]; int n, m; cin >> n; for(int i = 0; i < n; i ++) { cin >> str; insertWord(str); } cin >> m; for(int i = 0; i < m; i ++) { cin >> str; ans = 0; queryWord(str); cout << ans << endl; } return 0; }
相关文章推荐
- Javascript 保存到本地
- HDU 1023.Train Problem II【大卡特兰数】【9月25】
- 启动mysql服务命令
- Android四大组件之--BroadcastReceiver--判断网络连接
- Swift - 让StoryBoard设计视图,程序运行时都使用横屏形式
- Sql-事务
- 交叉验证
- Linux服务器数据备份
- Android中LayoutParams总结和用法
- shell脚本学习 二
- R文件不能生成问题解决记录
- 命名空间
- Android Lollipop 新特性 - Palette
- 在实验中训练样本的选择和matlab代码展示(自己在实验中的亲身的经历)
- :亿级Web系统搭建——单机到分布式集群
- 函数回调(有参数)
- Javaweb 学习笔记之文件上传和下载-01
- 机房收费系统项目开发总结报告
- 谈谈SQL 语句的优化技术 (2)
- Perfect Cubes - 1543