zoukankan      html  css  js  c++  java
  • [置顶] <hduoj>统计难题(字典树)

    统计难题

    Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
    Total Submission(s): 10043    Accepted Submission(s): 4077


    Problem Description
    Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
     

    Input
    输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

    注意:本题只有一组测试数据,处理到文件结束.
     

    Output
    对于每个提问,给出以该字符串为前缀的单词的数量.
     

    Sample Input
    banana band bee absolute acm ba b band abc
     

    Sample Output
    2 3 1 0
     

    Author
    Ignatius.L
     

    Recommend
    Ignatius.L
    这题应用字典树去解很方便。初次使用字典树,代码不好,看的朋友见笑了。
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    
    class Tier
    {
    public:
        int cnt;//记录子串单词数
        Tier *next[26];//26个字母
        Tier()//创建对象时自动调用此构造函数进行初始化
        {
            cnt=1;
            for(int i=0;i<26;i++)
                next[i]=NULL;
        }
    }*root;
    
    int main()
    {
        char word[11];
        int len;
        root=new Tier;
        
        while(gets(word))
        {
            len=strlen(word);
            if(!len) break;
            //将输入的单词加入字典树中
            Tier *temp=root;
            for(int i=0;i<len;i++)
            {
                int k=word[i]-'a';
                if(temp->next[k]!=NULL)
                {
                    temp=temp->next[k];
                    temp->cnt++;
                }
                else
                {
                    temp->next[k]=new Tier;
                    temp=temp->next[k];
                }
            }//insert for
        }//while
        
        while(gets(word))
        {
            int i;
            len=strlen(word);
            //在生成的字典树中寻找输入的单词
            Tier* temp=root;
            for(i=0;i<len;i++)
            {
                int k=word[i]-'a';
                if(temp->next[k]!=NULL)
                {
                    temp=temp->next[k];
                }
                else
                {
                    break;
                }
            }//for
            if(i==len) printf("%d\n",temp->cnt);//整一个单词能在树中找到
            else puts("0");//i!=len,则这个单词至少有一个字母是树中木有的
        }//while
        return 0;
    }
    

     
  • 相关阅读:
    [洛谷P2745] [USACO5.3]窗体面积Window Area
    [洛谷P2751] [USACO4.2]工序安排Job Processing
    [洛谷P2738] [USACO4.1]篱笆回路Fence Loops
    [洛谷P4609] [FJOI2016]建筑师
    [洛谷P3228] [HNOI2013]数列
    解决Qt5使用SSL的“qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method”错误
    qt查看是否支持SSL
    qt获取依赖的openssl的版本
    qt关闭ssl验证,解决不能正常使用自签署ssl证书API的问题
    使用OpenSSL创建HTTPS所使用的SSL证书
  • 原文地址:https://www.cnblogs.com/cszlg/p/2910502.html
Copyright © 2011-2022 走看看