HDU 1251 统计难题 (字典树基本模板,有详细注释)

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

 

题目的意思已经很明白了:统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

我这就直接给字典树基础模板了,给了一些注释,望各位能理解

 

#include <iostream>
#include <cstring>
using namespace std;
typedef struct tree //建立节点
{
    int num;
    struct tree *br[26]; //每一层有26个字母
}Node;

Node *head;
void Tree_Insert(char str[])//建树
{
    Node *t,*s=head;
    int i,j;
    int len=strlen(str);
    for(i=0;i<len;i++)
    {
        int id=str[i]-'a'; 
        if(s->br[id]==NULL) 
        {
            t=new Node; //在这个字母下面在开辟新的结点
            for(j=0;j<=25;j++)//初始化新结点
	    {
                t->br[j] = NULL;
            }
            t->num=0;
            s->br[id]=t;  //标记这个结点链接的子树指针
        }
        s=s->br[id]; //s指向下一个结点
        s->num ++;  //经过这个点的次数
    }
}
int Tree_Find(char str[]) //搜索过程,从每位字母开始搜
{
    Node *s = head;
    int count;
    int len=strlen(str);
    for(int i=0;i<len;i++)
	{
        int Id=str[i]-'a';
        if(s->br[Id]==NULL)
        {
            count=0;
            return count ;
        }
        else
	{
            s=s->br[Id];
            count=s->num;
        }
        
    }
    return count;
}
int main()
{
    int i;
    head=new Node; //头结点
    for(i=0;i<=25;i++)//26个结点,初始化
    {
        head->br[i]=NULL; 
        head->num=0;
    }
    char tem[15];
    while(gets(tem),strcmp(tem,""))
   {
        Tree_Insert(tem);  //建树
    }
    while(gets(tem))
	{
        cout<<Tree_Find(tem)<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值