统计难题(hdu1251字典树)

题意:统计一某个单词为前缀的单词的数量。

思路:简单的字典树。

字典树的操作就三个一个是初始化,一个是插入建树,另一个查找。

统计前缀的数量,每读入一个单词,像树的深度遍历一样一层一层,如果节点存在该节点的出现次数+1,如果该节点没有出现,则申请一个空间,初始化该点,继续搜索

单词的查找,就是树的深度遍历,找到后输出他的出现次数

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

struct Trie
{
    struct Trie * child[26];
    int n;
};
struct Trie * root;
void insert(char * str)
{
    int i,j,len;
    len = strlen(str);
    struct Trie * node,*tnode;
    node = root;
    if(len == 0)
        return ;
    for(i = 0; i < len; i++)
    {
        if(node -> child[str[i]-'a'] != NULL)
        {
            node = node -> child[str[i]-'a'];
            node -> n = node -> n + 1;
        }
        else
        {
            tnode = (struct Trie*)malloc(sizeof(struct Trie));
            for(j = 0; j < 26; j++)
            {
                tnode -> child[j] = NULL;
            }
            node -> child[str[i]-'a'] = tnode;
            node = tnode;
            node -> n = 1;
        }
    }
}

int find(char* str)
{
    int i,len;
    struct Trie * node;
    node = root;
    len = strlen(str);
    if(len == 0)
        return 0;
    for(i = 0;i < len; i++)
    {
        if(node -> child[str[i]-'a'] != NULL)
        {
            node = node -> child[str[i]-'a'];
        }
        else
            return 0;
    }
    return node -> n;
}

int main()
{
    char s[1000];
    int i;
    root = (struct Trie*)malloc(sizeof(struct Trie));
    for(i = 0; i < 26; i++)
        root -> child[i] = NULL;
    //root -> n = 2;
    while(gets(s))
    {        
        if(s[0] == '\0')
            break;
        else
        {
            insert(s);
        }
    }
    while(scanf("%s",s) != EOF)
    {
        printf("%d\n",find(s));
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值