HDU1251——统计难题(字典树模板)

本文介绍了一种使用前缀树(Trie)的数据结构来高效处理字符串集合的方法。通过C语言实现了一个基本的Trie结构,包括创建节点、插入字符串和搜索字符串的功能。文章详细解释了每个操作的具体实现,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最基础的模板,统计前缀。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;



const int MAX=26;

typedef struct TrieNode
{
    int nCount;  // 该节点前缀 出现的次数
    struct TrieNode *next[MAX]; //该节点的后续节点
} TrieNode;

TrieNode Memory[1000000]; //先分配好内存。 malloc 较为费时
int allocp = 0;

//初始化一个节点。nCount计数为1, next都为null
TrieNode * createTrieNode()
{
    TrieNode * tmp = &Memory[allocp++];
    tmp->nCount = 1;
    for (int i = 0; i < MAX; i++)
        tmp->next[i] = NULL;
    return tmp;
}

void insertTrie(TrieNode * * pRoot, char * str)
{
    TrieNode * tmp = *pRoot;
    int i = 0, k;
    //一个一个的插入字符
    while (str[i])
    {
        k = str[i] - 'a'; //当前字符 应该插入的位置
        if (tmp->next[k])
        {
            tmp->next[k]->nCount++;
        }
        else
        {
            tmp->next[k] = createTrieNode();
        }

        tmp = tmp->next[k];
        i++; //移到下一个字符
    }

}

int searchTrie(TrieNode * root, char * str)
{
    if (root == NULL)
        return 0;
    TrieNode * tmp = root;
    int i = 0, k;
    while (str[i])
    {
        k = str[i] - 'a';
        if (tmp->next[k])
        {
            tmp = tmp->next[k];
        }
        else
            return 0;
        i++;
    }
    return tmp->nCount; //返回最后的那个字符  所在节点的 nCount
}

int main(void)
{
    char s[11];
    TrieNode *Root = createTrieNode();
    while (gets(s) && s[0] != '\0') //读入0 结束
    {
        insertTrie(&Root, s);
    }

    while (gets(s)) //查询输入的字符串
    {
        printf("%d\n", searchTrie(Root, s));
    }

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值