hiho第二周——Trie树
2015-06-09 22:50
393 查看
hiho第二周——Trie树
题目链接:http://hihocoder.com/contest/hiho2/problem/1注意点
结构体的构造函数建树:注意先给子节点分配好内存,在移动cur指针
查询:注意边界情况,cur可能在循环完成后指向空节点
可执行代码
#include <iostream> #include <fstream> #include <string> using namespace std; typedef struct Node { //结构体的构造函数 Node() { num = 0; for(int i = 0;i<26;i++) child[i] = NULL; } int num; struct Node* child[26]; }Node; //建树 void insert(Node *root,string str) { Node * cur = root; for(int i = 0;i<str.size();i++) { if(cur->child[str[i]-'a'] == NULL) { cur->child[str[i]-'a'] = new Node(); } cur = cur->child[str[i]-'a']; cur->num = cur->num + 1; } return; } int query(Node *root,string str) { Node * cur = root; for(int i = 0;i < str.size();i++) { if(cur == NULL) return 0; cur = cur->child[str[i]-'a']; } if(cur == NULL) return 0; return cur->num; } int main() { ifstream cin("input.txt"); int N; string str; Node *root = new Node(); cin>>N; while(N--) { cin>>str; insert(root,str); } cin>>N; while(N--) { cin>>str; cout<<query(root,str)<<endl; } return 0; }
相关文章推荐
- Trie树_字典树(字符串排序)简介及实现
- Trie树与后缀树
- hihoCoder第二周:Trie树
- poj_2513
- hdu 1305 Immediate Decodability
- 【数据结构-trie树】trie数实现单词查询和单词统计
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配
- Trie树应用:统计与匹配