功能说明:每行输入一个单词,插入字典树 输入空行结束插入 ;
继续输入字符串,输出字典树中以此字符串为前缀的单词数目。
输入输出实例:
输入:
banana
band
bee
absolute
acm
ba
b
band
abc
输出:
2
3
1
0
#include "stdio.h"
#include "string.h"
const int N=5000;
typedef struct Node{
Node *ch[26];
int num;
};
Node a[N],*root;
char s[11];
int p=0;
Node *newNode(){
memset(a[p].ch,0,sizeof(a[p].ch));
a[p].num=0;
return &a[p++];
}
void insert(char *s){
Node *cur=root;
cur->num++;
while(*s!='\0'){
int t=*(s++)-'a';
if(cur->ch[t]==NULL)
cur->ch[t]=newNode();
cur=cur->ch[t];
cur->num++;
}
}
int getans(char *s){
Node *cur=root;
while(*s!='\0'){
int t=*(s++)-'a';
if(cur->ch[t]==NULL) return 0;
cur=cur->ch[t];
}
return cur->num;
}
int main(){
root=newNode();
gets(s);
while(s[0]!='\0'){
insert(s);
gets(s);
}
while(scanf("%s",s)!=EOF)
printf("%d\n",getans(s));
return 0;
}