杭电 HOJ 1251 统计难题 解题报告

    初看以为很简单的。。。当然,直接数组保存单词然后遍历查询一定会超时。在网上搜索了一下,看到“字典树”的概念。自己也没看他的代码,但是却找到了方法了。

    字母一共有26个。建立一个结构,里面保存一个大小为26的指针数组,然后读入单词,节点+1。额,看代码更清楚些

#include <iostream>
#include <string>
using namespace std;

class word
{
public:
    word()
    {
        memset(s,0,sizeof(s));
        num=0;
    }
    word *s[26];
    int num;
};

int main()
{
    int i,len,t;
    char str[100];
    word *head,*p;
    head=new word;
    while(cin.getline(str,sizeof(str)) && str[0]!='\0')
    {
        p=head;
        len=strlen(str);
        for(i=0;i<len;i++)
        {
            t=str[i]-'a';
            if(p->s[t]==0)
                p->s[t]=new word;
            p=p->s[t];
            p->num++;
        }
    }
    while(cin>>str)
    {
        p=head;
        len=strlen(str);
        for(i=0;i<len;i++)
        {
            t=str[i]-'a';
            if(p->s[t]==0)
            {
                i=-1;
                break;
            }
            p=p->s[t];
        }
        if(i==-1)
            cout<<0<<endl;
        else
            cout<<p->num<<endl;
    }
}

 

转载于:https://www.cnblogs.com/IT-BOY/archive/2013/02/27/2934991.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值