/*
字典树的应用
hdu_1251 用于研究下字典树
*/
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef struct node
{
struct node *br[26]; //对应的是26个英文字母(部分大小写)
int num; //num就是指该节点的孩子节点的数目
//也就是以从根节点到该节点的路径上所有字母组成的字符串为前缀的字符串的数目
} Node;
Node *head;
void Tree_Insert(char str[]) //插入
{
Node *t,*s = head;
int i , j;
int len = strlen(str) - 1;
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) - 1;
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 , j;
char str[12];
head = new Node;
for(i = 0 ; i < 26 ; i++)
{
head->br[i] = NULL;
head->num = 0;
}
while(gets(str) && strcmp(str,""))
{
Tree_Insert(str);
}
while(gets(str))
{
printf("%d\n",Tree_Find(str));
}
return 0;
}
转载于:https://www.cnblogs.com/zuckerTT/archive/2011/10/28/2228105.html