hdoj 1251 统计难题(字典树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

思路分析:该问题要求求出以某个字符串为前缀的单词数目,通过使用字典树,在字典树中添加count记录通过该结点的单词数目即可;

查找时找到前缀的最后一个单词的结点的count值即为所求;

 

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int KIND = 26;
const int MAX_N = 20;
struct Node
{
    Node *next[26];
    int count;
    Node ()
    {
        count = 0;
        memset(next, 0, sizeof(next));
    }
};

void InsertTrie(Node *root, char *str)
{
    Node *p = root;
    int i = 0, k = 0;

    while (str[i])
    {
        k = str[i] - 'a';
        if (!p->next[k])
            p->next[k] = new Node();
        p = p->next[k];
        p->count++;
        ++i;
    }
}

int Find(Node *root, char *str)
{
    int i = 0, k = 0;
    Node *p = root;

    while (str[i])
    {
        k = str[i] - 'a';
        if (!p->next[k])
            return 0;
        p = p->next[k];
        ++i;
    }
    return p->count;
}

int main()
{
    int ans = 0;
    char str[MAX_N];
    Node *root = new Node();

    while (gets(str) && strcmp(str,"") != 0)
        InsertTrie(root, str);
    while (gets(str))
    {
        ans = Find(root, str);
        printf("%d\n", ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/tallisHe/p/4663051.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值