trie树模板(统计难题)
来源:互联网 发布:linux 网络配置dhcp 编辑:程序博客网 时间:2024/05/21 22:32
统计难题 View CodeView Code
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 36675 Accepted Submission(s): 13637
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2310
Author
Ignatius.L
点一下查找树的要点:
1.根节点是个空点,只有形式上的起点作用(插入、查找时从它开始)
2.熟练应用指针,才能避免过多的调试
指针型
#include<iostream>#include<cstdio>#include<cstring>using namespace std;struct node{ int k;bool ift; node *ch[26];}*root;node *create(){ node *d=new(node); memset(d->ch,0,sizeof(d->ch)); d->k=0; d->ift=0; return d;}void insert(char *s){ node *q=root; char *p=s; while(*p) { int id=*p-'a'; if(q->ch[id]==NULL)q->ch[id]=create(); q=q->ch[id]; p++; q->k++; } q->ift=1;}int search(char *s){ node *q=root; char *p=s; while(*p) { int id=*p-'a'; q=q->ch[id]; p++; if(q==NULL)return 0; } return q->k;}int main(){ root=create();char s[12]; bool r=0; while(gets(s)) { if(strlen(s)==0)break; insert(s); } while(gets(s))cout<<search(s)<<endl;}
数组模拟
#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;int trie[400001][26],len,root,tot,sum[400001];bool p;char s[11];void insert(){ len=strlen(s); root=0; for(int i=0;i<len;i++) { int id=s[i]-'a'; if(!trie[root][id]) trie[root][id]=++tot; sum[trie[root][id]]++; root=trie[root][id]; }}int search(){ root=0; len=strlen(s); for(int i=0;i<len;i++) { int id=s[i]-'a'; if(!trie[root][id]) return 0; root=trie[root][id]; } return sum[root];}int main(){ while(gets(s)) { if(!p) { if(strlen(s)) insert(); else p=1; } else printf("%d\n",search()); }}
0 0
- trie树模板(统计难题)
- hdu 1251 统计难题(trie树)
- HDOJ1251-统计难题(trie树入门)
- HDU1251 统计难题(Trie树)
- hdu 1251 统计难题 (trie树)
- HDU 1251 统计难题 (Trie树 模板题)
- HDU1251 统计难题 【trie树】
- HDU1251统计难题 trie树
- HDU1251 统计难题(Trie树)
- HDU1251 统计难题(Trie)
- [复习][HDU1251]字典树(trie树)统计难题
- HDU 1251 统计难题 字典树入门(Trie)
- HDU 1251 统计难题 (字符串-Trie树)
- HDU 1251 统计难题(trie树入门)
- (字典树Trie Tree)HDU 1251 统计难题
- HDU1251 统计难题(字典树模板)
- HDU1251统计难题(字典树模板)
- 统计难题(字典树模板)
- 欧拉通路、回路
- Haar+Adaboost级联分类器分解(二…
- eclipse插件开发(一)
- 你有多久没有看过星星
- Haar+Adaboost级联分类器分解(三…
- trie树模板(统计难题)
- Source Insight崩溃的解决办法
- github快速入门(一)
- SPFA(热浪)
- 更换linux内核的开机启动logo
- git 几款好用的客户端工具
- Candies
- eclipse代码左虚线对齐设置
- 启用linux内核对usb摄像头的支持