HDU 1251 统计难题(经典字典树)

xiaoxiao2021-02-28  134

原题

统计难题

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others) Total Submission(s): 41097 Accepted Submission(s): 14840

Problem Description

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

Input

输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串. 注意:本题只有一组测试数据,处理到文件结束.

Output

对于每个提问,给出以该字符串为前缀的单词的数量. Sample Input banana band bee absolute acm ba b band abc

Sample Output

2 3 1 0

涉及知识及算法

字典树: 又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。 ——百度百科

代码

#include <iostream> #include <cstdio> #include <cstring> #define N 26 using namespace std; typedef struct Tire{ int num; Tire *next[N]; Tire(){ num=0; for(int i=0;i<N;i++) next[i]=NULL; } }Tire; Tire root; void Insert(char word[]){ Tire *p=&root; for(int i=0;word[i];i++){ if(p->next[word[i]-'a']==NULL) p->next[word[i]-'a']=new Tire; p=p->next[word[i]-'a']; p->num++; } } int Find(char word[]){ Tire *p=&root; for(int i=0;word[i];i++){ if(p->next[word[i]-'a']==NULL) return 0; p=p->next[word[i]-'a']; } return p->num; } int main(){ char word[11]; while(cin.getline(word,12)){ if(strlen(word)==0||word[0]==' ') break; Insert(word); } while(scanf("%s",word)!=EOF) printf("%d\n",Find(word)); return 0; }

转载请注明原文地址: https://www.6miu.com/read-28615.html

最新回复(0)