hdu 1251 统计难题(trie 树的简单应用)
2015-05-06 21:49
204 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题意:给你多个字符串,求以某个字符串为前缀的字符串数量。
思路:简单的trie数应用,在trie的数据结构中增加一个存储到当前节点字符串出现的次数,在插入的过程中维护即可。
code:
题意:给你多个字符串,求以某个字符串为前缀的字符串数量。
思路:简单的trie数应用,在trie的数据结构中增加一个存储到当前节点字符串出现的次数,在插入的过程中维护即可。
code:
#include <cstdio> #include <cstring> const int KIND = 26; struct TrieNode { int num; // 遍历到该结点形成的字符串出现的次数 TrieNode* next[KIND]; TrieNode() { num = 1; for (int i = 0; i < KIND; ++i) next[i] = NULL; } }; TrieNode* root = NULL; void Insert(char* x) { TrieNode* temp = root; if (root == NULL) // 预判 { temp = new TrieNode(); root = temp; } int len = strlen(x); for (int i = 0; i < len; ++i) { int curr = x[i] - 'a'; if (temp->next[curr] != NULL) ++(temp->next[curr]->num); // 已经存在 else temp->next[curr] = new TrieNode(); // 不存在 temp = temp->next[curr]; } } int Search(char* x) { int ret = 0; if (root == NULL) return ret; // 预判 TrieNode* temp = root; int len = strlen(x); for (int i = 0; i < len; ++i) { int curr = x[i] - 'a'; if (temp->next[curr] == NULL) return 0; temp = temp->next[curr]; ret = temp->num; } return ret; } void Release(TrieNode* root) { if (NULL == root) return; for (int i = 0; i < KIND; ++i) { if (root->next[i] != NULL) Release(root->next[i]); } delete root; root = NULL; } int main() { char str[10]; while (gets(str)) { if (str[0] == '\0') { while (gets(str)) printf("%d\n", Search(str)); } else Insert(str); } Release(root); return 0; }
相关文章推荐
- HDU 1251 统计难题(trie简单应用)
- hdu-1251统计难题-字典树的简单应用
- HDOJ 1251 统计难题(j简单的字典树trie的应用)
- hdu 1251 统计难题 trie
- hdu_1251 统计难题 trie模版
- HDU 1251 统计难题(Trie tree)
- HDU-1251 统计难题(字典树 trie)
- hdu 1251 统计难题 Trie
- HDU--1251 -- 统计难题 [字典树基本应用] [用数组事先分配空间以节约时间]
- hdu_1251 统计难题 trie模版
- (字典树Trie Tree)HDU 1251 统计难题
- hdu 1251 统计难题(trie)
- hdu 1251 统计难题(Trie 水题)
- HDU 1251 统计难题 (Trie)
- hdu_1251 统计难题 trie模版
- hdu 1251统计难题(trie)
- hdu 1251 统计难题(数据结构:trie)
- hdu_1251 统计难题 trie模版
- HDU1251——trie模板——统计难题
- hdu_1251 统计难题 trie模版