HDU 1251 统计难题 (字典树)
来源:互联网 发布:网络主播loli王春雨 编辑:程序博客网 时间:2024/06/03 13:10
问题描述:
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
大致题意:
如题。
简单字典树。
ac代码:
#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <vector>#include <queue>using namespace std;const int MAXN = 26;struct Trie{ Trie *Next[MAXN]; int Flag; Trie() { Flag = 1; memset(Next, NULL, sizeof(Next)); }}*root;void Insert(char *str)//插入{ int len = strlen(str); Trie *p = root, *q; // 将str的每一个字符插入trie树 for(int i=0; i<len; ++i) { int id = str[i] - 'a'; // 如果没有边,则新建一个trie节点,产生一条边,用以代表该字符 if(p->Next[id] == NULL) { q = new Trie(); p->Next[id] = q; p = p->Next[id]; } // 如果存在边,则沿着该边走 else { p = p->Next[id]; // 累加以该信息为前缀的信息个数 ++(p->Flag); } }}int Query(char *str)//查询操作{ int len = strlen(str); Trie *p = root; // 在trie树上顺序搜索str的每一个字符 for(int i=0; i<len; ++i) { int id = str[i] - 'a'; p = p->Next[id]; // 若为空集,表示不存以此为前缀的信息 if(p == NULL) return 0; } // 返回以该信息为前缀的信息个数 return p->Flag;}void Free(Trie* T)//删除{ if(T == NULL) return; // 释放trie树的每一个节点占用的内存 for(int i=0; i<MAXN; ++i) { if(T->Next[i]) Free(T->Next[i]); } delete(T);}int main(){ char ch[15]; root=new Trie(); while(gets(ch)) { if(ch[0]=='\0') break; Insert(ch); } while(~scanf("%s",ch)) { cout<<Query(ch)<<endl; } Free(root); return 0;}
0 0
- HDU 1251统计难题(字典树)
- hdu 1251 统计难题(字典树)
- hdu 1251 统计难题(字典树)
- hdu 1251 统计难题(字典树)
- hdu 1251 统计难题 (字典树)
- hdu 1251 统计难题(字典树)
- HDU 1251 统计难题(字典树)
- HDU 1251 统计难题(字典树)
- HDU 1251 统计难题(字典树)
- HDU-#1251 统计难题(字典树)
- hdu 1251 统计难题(字典树)
- HDU - 1251 - 统计难题(字典树)
- HDU 1251 统计难题(字典树)
- HDU 1251统计难题 (字典树)
- hdu 1251 统计难题(字典树)
- hdu 1251 统计难题(字典树)
- HDU 1251 统计难题(字典树)
- HDU-1251 统计难题(字典树)
- java正则表达式
- C++11 narrowing convertions(缩窄转换)
- (01)关于我在使用百度地图开发常见到的问题
- 输入密码或金额的显示和隐藏(续)
- Foxit Mobile PDF SDK尝鲜-IOS篇(1)-Run the Demo
- HDU 1251 统计难题 (字典树)
- spring AOP自学
- 读《Java并发性和多线程》有感
- 原生JS控制CSS样式语法对照
- CString与int、float之间的转换
- Make Query Layer在Model Builder中的使用
- centos7 开启
- LoadRunner自动关联
- RecyclerView下拉刷新和上拉加载更多