zoukankan      html  css  js  c++  java
  • 字典(Trie树)

    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

    //字典字典字典树
    //用指针写真好啊,好写还容易理解。(就是别忘了更新指针!!卡死我了!) 
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    
    using namespace std;
    int n,m;
    char s[8];
    struct trie
    {
        trie *next[26];
    }*root;
    
    trie *cr()
    {
        trie *pt=new trie;
        memset(pt->next,0,sizeof pt->next);
        return pt;
    }
    
    void insert(char *word)//插入单词 
    {
        trie *p=root;
        char *q=word;
        while(*q)
        {
            int id=*q-'a';
            if(p->next[id]==NULL)
              p->next[id]=cr();
            p=p->next[id];
            q++;
        }
    }
    
    bool search(char *word)
    {
        trie *p=root;
        char *q=word;
        int now=0;
        while(*q)
        {
            int id=*q-'a';
            if(p->next[id])
              {
                  q++;
                  p=p->next[id];//更新指针AAAA! 
                continue;//能找到就继续 
              }
             return false;
        }
        return true;
    }
    
    int main()
    {
        scanf("%d",&n);
        root=cr();
        for(int i=1;i<=n;i++)
        {
            scanf("%s",s);
            insert(s);
        }
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            scanf("%s",s);
            if(search(s)) printf("YES
    ");
            else printf("NO
    ");
        }
        return 0;
    } 
    心若向阳,无言悲伤
    折花枝,恨花枝,准拟花开人共卮,开时人去时。 怕相思,已相思,轮到相思没处辞,眉间露一丝。
  • 相关阅读:
    006_01XML简介
    005_01文档对象模型DOM
    004_01浏览器对象模型BOM
    SpringBoot的学习【4.快速实现一个SpringBoo的应用】
    SpringBoot的学习【3.HelloWorld配置细节】
    年中总结
    由一次报错引发的对于Spring创建对象的理解
    SpringBoot的学习【2.分析HelloWorld的依赖】
    SpringBoot的学习【1.初学之HelloWorld】
    IllegalStateException
  • 原文地址:https://www.cnblogs.com/L-Memory/p/6290800.html
Copyright © 2011-2022 走看看