码迷,mamicode.com
首页 > 其他好文 > 详细

AC日记——字典 codevs 4189

时间:2017-01-16 19:58:05      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:ref   style   单词   时间   []   font   这一   line   一段   

4189 字典

 

 时间限制: 1 s
 空间限制: 256000 KB
 题目等级 : 大师 Master
 
 
题目描述 Description

最经,skyzhong得到了一本好厉害的字典,这个字典里整整有n个单词(1<=n<=200000)

现在skyzhong需要在字典里查询以某一段字母开头的单词

如:skyzhong想查询a

那么只要是a开头的单词就可以了

skyzhong只想知道里面有没有这一个单词(因为没有他就不查了)

若有,请输出YES。若没有,请输出NO

 

输入描述 Input Description

第一行一个数n

第二行到第n+1行,一行一个字符串

再下一行一个数m,表示skyzhong想要查询的次数

接着m行,一行一个字符串,表示skyzhong想要查的东西

输出描述 Output Description

共m行,若有这字串输出YES,否则输出NO

样例输入 Sample Input

3

asd

asfdghj

asfd

3

asd

asdghj

asf

样例输出 Sample Output

YES

NO

YES

数据范围及提示 Data Size & Hint

字符串只有小写字母,且长度≤8

 

思路:

  裸tire树;

 

来,上代码:

#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

struct TreeNode {
    bool if_[26];
    
    TreeNode *word[26];
};

class TireTreeType {
    private:
        TreeNode *null,*root;
        
        inline void Insert_Tire(TreeNode *now,char str[])
        {
            int len=strlen(str);
            for(int i=0;i<len;i++)
            {
                if(!now->if_[str[i]-a])
                {
                    now->if_[str[i]-a]=true;
                    now->word[str[i]-a]=new TreeNode;
                    for(int j=0;j<26;j++) now->word[str[i]-a]->word[j]=null;
                }
                now=now->word[str[i]-a];
            }
        }
        
        inline bool Find_Tire(TreeNode *now,char str[])
        {
            int len=strlen(str);
            for(int i=0;i<len;i++)
            {
                if(now->if_[str[i]-a])
                {
                    now=now->word[str[i]-a];
                }
                else return false;
            }
            return true;
        }
        
    public:
        TireTreeType()
        {
            null=new TreeNode;
            for(int i=0;i<26;i++) null->word[i]=null;
            root=new TreeNode;
            for(int i=0;i<26;i++) root->word[i]=null;
        }
        
        void Insert(char str[])
        {
            Insert_Tire(root,str);
        }
        
        bool Find(char str[])
        {
            return Find_Tire(root,str);
        }
};
class TireTreeType tree;

int n,m;

char Cgets[10];

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",Cgets);
        tree.Insert(Cgets);
    }
    scanf("%d",&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%s",Cgets);
        if(tree.Find(Cgets)) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

 

AC日记——字典 codevs 4189

标签:ref   style   单词   时间   []   font   这一   line   一段   

原文地址:http://www.cnblogs.com/IUUUUUUUskyyy/p/6290772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!