统计难题
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
字典树:
插入字符串
1. 设置当前节点为根节点,设置当前字符为插入字符串中的首个字符;
2. 在当前节点的子节点上搜索当前字符,若存在,则将当前节点设为值为当前字符的子节点;否则新建一个值为当前字符的子节点,并将当前结点设置为新创建的节点。.
3. 将当前字符设置为串中的下个字符,若当前字符为0,则结束;否则转2.
l 性质
根节点不包含字符,除根节点外的每一个节点都只包含一个字符。
从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
每个节点的所有子节点包含的字符都不相同。
#include<iostream>
# include<cstring>
#include<cstdio>
using namespace std;
const int maxn=500000;
char wen[20];
struct node{
int tot;
int child[26]; //储存子节点,最多为26个;
node()
{
tot=0;
memset(child,0,sizeof(child));
}
}tree[maxn];
int sz=0;
void insert(char *s)
{
int u=0;
int h=strlen(s);
for(int i=0;i<h;i++)
{
int pos=s[i]-'a';
if(tree[u].child[pos]==0)
tree[u].child[pos]=++sz;
u=tree[u].child[pos]; // 将子节点作为母结点,往下走;
tree[u].tot++;
}
}
int find(char *t)
{
int u=0;
int h=strlen(t);
for(int i=0;i<h;i++)
{
int pos=t[i]-'a';
if(tree[u].child[pos]==0)
return 0;
u=tree[u].child[pos];
}
return tree[u].tot;
}
int main()
{
while(gets(wen))
{
if(strlen(wen)==0) break;
insert(wen);
}
while(gets(wen))
{
printf("%d\n",find(wen));
}
return 0;
}