字典树hdu1251

字典树:
用于统计、排序和保存大量的字符串,它的优点是节约了存储空间,并且查找的效率很高。

题意:
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

思路:用字典树存储单词表,在建树的过程中就记录该单词出现的次数,然后查询的时候,直接输出对应的单词的次数就行了。比如样例中单词表为”banana band bee absolute acm”,这样的话,’b’出现的次数就是3次,’ba’出现的次数就是2次。

#include <iostream>
using namespace std;
#include <cstdio>
#include <cstring>
#include <malloc.h>
struct Trie
{
    Trie *next[26];
    int num;
};
void Init(Trie *t)  //初始化结点
{
    t->num = 0;
    for(int i = 0; i < 26; i++)
    {
        t->next[i] = NULL;
    }
}
void Insert(Trie *root, char s[])
{
    Trie *t = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(t->next[s[i]-'a'] == NULL) //如果该结点为出现过,那就新加一个分支
        {
            t->next[s[i]-'a'] = (Trie *)malloc(sizeof(Trie));
            Init(t->next[s[i]-'a']);
        }
        t = t->next[s[i] - 'a']; //指向孩子结点
        t->num++; //次数加一
    }
}
int Query(Trie *root, char s[])  //查找字符串
{
    Trie *t = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        if(t->next[s[i]-'a'] == NULL)  //没有该字符串,返回0,证明出现次数为0次
            return 0;
        t = t->next[s[i]-'a'];
    } 
    return t->num; //匹配完成,返回出现次数
}
int main()
{
    char a[30];
    Trie *root = (Trie*)malloc(sizeof(Trie));
    Init(root);
    while(gets(a) && a[0])
    {
        Insert(root, a);
    }
    while(gets(a))
    {
        printf("%d\n", Query(root, a));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值