统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 10712 Accepted Submission(s): 4429
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<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 26
struct dirtrie
{
struct dirtrie *child[N];
int n;//在此表示有多少关键字为从根到此结点的的串的公共前缀
};
struct dirtrie *root;//建立空的根节点,里面不存放任何信息
void initial(struct dirtrie *p)//初始化字典树的结点
{
int i;
for(i=0;i<N;i++)
p->child[i]=NULL;
return ;
}
void insert(char *source)
{
int i,len;
struct dirtrie *curent,*newnode;//用于指向当前结点和申请新的结点
len=strlen(source);
if(len==0) return;
curent=root;
for(i=0;i<len;i++)
{
if(curent->child[source[i]-'a']!=0)
{
curent=curent->child[source[i]-'a'];//当前结点转移
curent->n=curent->n+1;//结点每重复一次,以此为前缀的串多一个,计数用的
}
else
{
newnode=(struct dirtrie *)malloc(sizeof(struct dirtrie));
initial(newnode);
curent->child[source[i]-'a']=newnode;//把当前结点和刚刚申请的新结点连接起来 ,千万不能省略
curent=newnode;
curent->n=1;
}
}
return ;
}
int find(char *source)
{
int i,len;
struct dirtrie *curent;
len=strlen(source);
if(len==0) return 0;
curent=root;
for(i=0;i<len;i++)
{
if(curent->child[source[i]-'a']!=NULL)
curent=curent->child[source[i]-'a'];
else return 0;
}
return curent->n;
}
int main()
{
char temp[11];
int i,k;
root=(struct dirtrie *)malloc(sizeof(struct dirtrie));
initial(root);
while(gets(temp),strcmp(temp,"")!=0)
insert(temp);
while(scanf("%s",temp)!=EOF)
{
k=find(temp);
printf("%d\n",k);
}
return 0;
}