hdu 1251

本文介绍了字典树的基础概念及实现方式,并通过实例演示了如何使用字典树解决实际问题。

字典树基础,没有什么难度,开始学习字典树的时候看着代码敲一遍就可以了,没有什么深入思考的地方(要会链表,要会链表,要会链表)

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

struct node{
    int cnt;
    struct node *next[26];
    node(){
        cnt = 0;
        for(int i = 0; i < 26; ++i)
            next[i] = NULL;
    }
};

void clear_root(node *p){
    for(int i = 0; i < 26; ++i)
        if(p->next[i] != NULL)
            clear_root(p->next[i]);
    delete p;
}
int main()
{
    char s[11];
    node *root = new node;
    while(gets(s)){
        if(strcmp(s, "") == 0)
            break;
        node *p = root;
        for(unsigned i = 0; i < strlen(s); ++i){
            int t = s[i] - 'a';
            if(p->next[t] == NULL){
                p->next[t] = new node;
            }
            p = p->next[t];
            p->cnt++;
        }
    }
    while(scanf("%s", s) != EOF){
        int ok = 1;
        node *p = root;
        for(unsigned i = 0; i < strlen(s); ++i){
            int t = s[i] - 'a';
            if(p->next[t] == NULL){
                printf("0\n");
                ok = 0;
                break;
            }
            p = p->next[t];
        }
        if(ok)
            printf("%d\n", p->cnt);
    }
    clear_root(root);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值