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

codeVS 4189 字典

时间:2018-09-05 10:27:41      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:can   algo   一个   ane   style   inline   for   default   esc   

题目描述 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 <map>
#include <algorithm>
using namespace std;
int trie[400001][26],pos;
inline void Insert(char *s) {
    int i = 0,c = 0;
    while(s[i]) {
        int d = s[i] - a;
        if(!trie[c][d]) {
            trie[c][d] = ++ pos;
        }
        c = trie[c][d];
        i ++;
    }
}
inline bool Query(char *s) {
    int i = 0,c = 0;
    while(s[i]) {
        int d = s[i] - a;
        if(!trie[c][d]) {
            return false;
        }
        c = trie[c][d];
        i ++;
    }
    return true;
}
int main() {
    char s[12];
    int n,m;
    scanf("%d",&n);
    for(int i = 0;i < n;i ++) {
        scanf("%s",s);
        Insert(s);
    }
    scanf("%d",&m);
    for(int i = 0;i < m;i ++) {
        scanf("%s",s);
        puts(Query(s) ? "YES" : "NO");
    }
}

 

codeVS 4189 字典

标签:can   algo   一个   ane   style   inline   for   default   esc   

原文地址:https://www.cnblogs.com/8023spz/p/9590392.html

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