链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
题目的意思已经很明白了:统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
我这就直接给字典树基础模板了,给了一些注释,望各位能理解
#include <iostream>
#include <cstring>
using namespace std;
typedef struct tree //建立节点
{
int num;
struct tree *br[26]; //每一层有26个字母
}Node;
Node *head;
void Tree_Insert(char str[])//建树
{
Node *t,*s=head;
int i,j;
int len=strlen(str);
for(i=0;i<len;i++)
{
int id=str[i]-'a';
if(s->br[id]==NULL)
{
t=new Node; //在这个字母下面在开辟新的结点
for(j=0;j<=25;j++)//初始化新结点
{
t->br[j] = NULL;
}
t->num=0;
s->br[id]=t; //标记这个结点链接的子树指针
}
s=s->br[id]; //s指向下一个结点
s->num ++; //经过这个点的次数
}
}
int Tree_Find(char str[]) //搜索过程,从每位字母开始搜
{
Node *s = head;
int count;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int Id=str[i]-'a';
if(s->br[Id]==NULL)
{
count=0;
return count ;
}
else
{
s=s->br[Id];
count=s->num;
}
}
return count;
}
int main()
{
int i;
head=new Node; //头结点
for(i=0;i<=25;i++)//26个结点,初始化
{
head->br[i]=NULL;
head->num=0;
}
char tem[15];
while(gets(tem),strcmp(tem,""))
{
Tree_Insert(tem); //建树
}
while(gets(tem))
{
cout<<Tree_Find(tem)<<endl;
}
return 0;
}