统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submission(s): 28980 Accepted Submission(s): 11389
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef struct Tree
{
struct Tree *next[26];
int v;
};
Tree *root;
void inits(char *op)
{
Tree *q=root,*p;
for(int i=0; i<strlen(op); i++)
{
int j=op[i]-'a';
if(q->next[j]==NULL)
{
p=new Tree;
for(int k=0; k<26; k++)
{
p->next[k]=NULL;
}
p->v=0;
q->next[j]=p;
}
q->v++;
q=q->next[j];
}
q->v++;
}
int finds(char *op)
{
Tree *q=root,*p;
for(int i=0;i<strlen(op);i++)
{
int j=op[i]-'a';
if(q->next[j]==NULL)
return 0;
q=q->next[j];
}
return q->v;
}
int main()
{
root=new Tree;
for(int i=0; i<26; i++)
root->next[i]=NULL;
root->v=0;
char op[15];
while(gets(op)&&op[0])
{
inits(op);
}
while(gets(op))
{
printf("%d\n",finds(op));
}
return 0;
}
字典树实现前缀统计
本文介绍了一个使用字典树(Trie)解决特定统计问题的方法。该问题要求统计一系列由小写字母组成的单词中,以给定字符串作为前缀的单词数量。文章提供了完整的C++代码实现,展示了如何构建字典树并进行高效查询。
997

被折叠的 条评论
为什么被折叠?



