banana band bee absolute acm ba b band abc
2 3 1 0
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char str[11];
struct node{
node *next[26];
int cnt;//表示一个字典树到此有多少相同前缀的数目
node(){//构造函数,创建结点时自动执行
cnt=0;
for(int i=0;i<26;i++)
next[i]=NULL;//将该节点的下面的26个节点初始化为空
}
};
void insert(node *p,char *str){
for(int i=0;str[i];i++){
int t=str[i]-'a';
if(p->next[t]==NULL)
p->next[t]=new node;//如果节点不存在,那么先new一个
p=p->next[t];//指针指向子孩子
p->cnt++;//计数器累加
}
}
int find(node *p,char *str){
for(int i=0;str[i];i++){
int t=str[i]-'a';
p=p->next[t];//指针指向子孩子
if(!p)//p为空就跳出
return 0;
}
return p->cnt;
}
int main(){
node *root=new node();
while(gets(str)&&strlen(str))
insert(root,str);
while(gets(str)){
int ans=find(root,str);
printf("%d\n",ans);
}
return 0;
}原文:http://blog.csdn.net/hpuhjl/article/details/41968747