hdu1251统计难题

本文介绍了一个简单的字典树实现及应用案例。通过C++代码演示了如何创建、插入、查找和删除字典树节点,旨在帮助读者理解并掌握字典树的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

才了解了字典树这个东西,就练练手了

点击题目打开链接

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX=26;
typedef struct Trie
{
    int count;
    bool terminal;
    Trie *son[MAX];
};
Trie *Create_New()
{
    Trie *temp=new Trie;
    temp->count=1; temp->terminal=false;
    for(int i=0;i<MAX;i++)
        temp->son[i]=NULL;
    return temp;
}

void Insert(Trie *pnt,char *s,int len)
{
    Trie *temp=pnt;
    for(int i=0;i<len;i++)
    {
        if(temp->son[s[i]-'a']==NULL) temp->son[s[i]-'a']=Create_New();
        else temp->son[s[i]-'a']->count++;
        temp=temp->son[s[i]-'a'];   //cout<<"         dsf\n"<<endl;
    }
    temp->terminal=true;
}

Trie *Find(Trie *pnt,char *s,int len)
{
    Trie *temp=pnt;
    for(int i=0;i<len;i++)
    {
        if(temp->son[s[i]-'a']!=NULL)
            temp=temp->son[s[i]-'a'];
        else
            return NULL;
    }
    return temp;
}

void Delete(Trie *pnt)
{
    if(pnt!=NULL)
    {
        for(int i=0;i<MAX;i++)
           if(pnt->son[i]!=NULL) Delete(pnt->son[i]);
        delete pnt;
        pnt=NULL;
    }
}

int main()
{
    char a[15],b[15];
    Trie *pnt=Create_New();
    while(gets(a) && a[0]!='\0')
    {
        int len=strlen(a);
        Insert(pnt,a,len);
    }
    while(~scanf("%s",b))
    {
        Trie *p=pnt;
        Trie *q=Find(p,b,strlen(b));
        if(q!=NULL)
        printf("%d\n",q->count);
        else printf("0\n");
    }
    Delete(pnt);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值