[字典树入门] HDOJ 1251 统计难题

不需要保存是否结束(isend),在插入时每经过一个节点,将该节点的计数器 +1,在查找时输出最后一个字符所在节点的cnt值即可;
PS:为什么加了删除树(del_Trie)会超时呢?

# include <cstdio>
# include <cstring>

# define LEN 10 + 1

struct node
{
    int cnt;
    node * next[26];
    node ()
    {
        cnt = 0;
        memset(next, 0, sizeof(next));
    }
};

void insert_Trie(node *root, char *s)
{
    int c;
    node *p = root;
    for (int i = 0; s[i]; ++i)
    {
        c = s[i]-'a';
        if (p->next[c] == NULL) p->next[c] = new node;
        p = p->next[c];
        ++(p->cnt);
    }
}

void build_Trie(node *root)
{
    char s[LEN];
    while (gets(s) , strcmp(s, ""))
    {
        insert_Trie(root, s);
    }
}

void del_Trie(node *p)
{
    for (int i = 0; i < 26; ++i)
        if (p->next[i]) del_Trie(p->next[i]);
    del_Trie(p);
}

int search(node *root, char *s)
{
    int c;
    node *p = root;
    for (; *s; ++s)
    {
        c = *s-'a';
        if (p->next[c]) p = p->next[c];
        else return 0;
        if ((*(s+1)) == 0) return p->cnt;
    }
    return 0;
}

void solve(void)
{
    char s[LEN];
    node *root = new node;
    build_Trie(root);
    while (gets(s) != NULL)
    {
        int ans = search(root, s);
        printf("%d\n", ans);
    }
    //del_Trie(root);     //TLE 
}

int main()
{
    solve();

    return 0;
}

转载于:https://www.cnblogs.com/JMDWQ/archive/2012/08/05/2624096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值