【tire树】hdu-1251

/*
字典树的应用
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值