HDU 1251 统计难题(字典树模板题)

题意:先输入单词再输入前缀,统计有相同前缀的单词有多少个。
坑点:一定要用c++交,用g++就MLE;

以前写的字典树从来没有delet这个环节,后来发现自己真是太戳了,借了人家的内存居然不还,补充一下delet模板

void del(struct Node *proot)
{
     for(int i=0;i<26;i++)
        if(proot->next[i]!=NULL) 
           del(proot->next[i]);
     delete(proot);//不要搞混了,这个delete是删除函数
}

好了,贴一份目前我认为是我标准字典树的模板:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;

struct Node
{
    struct Node *next[26];
    int cnt;
    Node()
    {
        cnt=0;
        for(int i=0;i<26;i++)
            next[i]=NULL;
    }
};
struct Node *root = new struct Node;
void inset(char *str)
{
    struct Node *cur = root;
    for(int i=0;str[i];i++)
    {
        if(cur->next[str[i]-'a']==NULL)
        {
            struct Node *newnode = new struct Node;
            cur->next[str[i]-'a'] = newnode;
        }
        cur = cur->next[str[i]-'a'];
        cur->cnt ++;
    }
    return; 
}
int query(char *str)
{
    struct Node *cur = root;
    for(int i=0;str[i];i++)
    {
        if(cur->next[str[i]-'a']!=NULL)
        {
            cur= cur->next[str[i]-'a'];
        }
        else return 0;
    }
    return cur->cnt;
}
void Delet(struct Node *proot)
{
    for(int i=0;i<26;i++)
      if(proot->next[i]!=NULL)
          Delet(proot->next[i]);
    delete proot;
}
int main()
{
    char str[20];
    while(gets(str) && str[0]!='\0')
    {
        inset(str);
    }

    while(gets(str))
    {
        printf("%d\n",query(str));
    }
    Delet(root);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值