哈哈,第一次用Trie树,从网上找了个模板改了改,然后自己写了search()。
题目很简单,就不解释了。
#include<stdio.h>
#include <string.h>
const int sonnum=26, base='a';
struct Trie{
int num; //记录有多少个单词能到达次,也即相同前缀的个位
//bool terminal; //判断是否是结束节点
struct Trie *son[sonnum];
Trie()
{
num=1;
// terminal=false;
memset(son,NULL,sizeof(son));
}
};
void Insert(Trie *root, char *s)
{
Trie *temp=root;
while(*s)
{
if(temp->son[*s-base]==NULL) //不存在 则建立
temp->son[*s-base]=new Trie();//NewTrie();
else
{
temp->son[*s-base]->num++;
}
temp=temp->son[*s-base];
s++;
}
//temp->terminal=true; //到达尾部,标记一个串
}
int search(Trie *root,char a[])
{
Trie *temp=root;
int i=0;
while(a[i])
{
if(temp->son[a[i]-base]!=NULL)
temp=temp->son[a[i]-base];
else return 0;
i++;
}
return temp->num;
}
int main()
{
char a[11];
Trie *root=new Trie();
while(gets(a))
{
if(a[0]=='\0')break;
Insert(root,a);
}
while(gets(a))
printf("%d\n",search(root,a));
return 0;
}