hdu1251
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct tree{
int lev;
struct tree*next[26];
};
tree root;
char str[12];
void creat_tree(char *str){
int i,j,len,id;
len=strlen(str);
tree *p=&root,*temp;
for(i=0;i<len;i++){
id=str[i]-'a';
if(p->next[id]==NULL){
temp=(tree *)malloc(sizeof(root));
temp->lev=1;
for(j=0;j<26;j++)
temp->next[j]=NULL;
p->next[id]=temp;
p=p->next[id];
}
else{
(p->next[id])->lev++;//说明该前缀出现,+1
p=p->next[id];
}
}
}
int search(char *str){
int i,j,len,id;
len=strlen(str);
tree *p=&root,*temp;
for(i=0;i<len;i++){
id=str[i]-'a';
p=p->next[id];
if(p==NULL)
return 0;
}
return p->lev;//返回前缀出现次数
}
int main(){
int i,j,ans;
for(i=0;i<26;i++)
root.next[i]=NULL;
while(gets(str)&&str[0]!='\0'){
creat_tree(str);
}
while(scanf("%s",str)!=EOF){//not NULL
ans=search(str);
printf("%d\n",ans);
}
return 0;
}
keep moving...

浙公网安备 33010602011771号