Codevs 4189 字典

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

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 int n,m; 
 6 struct node{
 7     node *next[26];
 8 }*root;
 9 node *create(){
10     node *p=new(node);
11     memset(p,0,sizeof(p->next));
12     return p;
13 }
14 char s[10];
15 void insert(char *w){
16     node *p=root;// 取根节点 
17     char *q=w;// 该单词的指针 
18     while(*q){// 单词没有到头 
19         int k=*q-'a';
20         if(p->next[k]==NULL)
21           p->next[k]=create();// 这个字符没有 -- 新建 
22         p=p->next[k];// p向下指 
23         q++;// 单词指针后移一位 
24     }
25 }
26 bool Judge(char *w){
27     node *p=root;char *q=w;
28     int now=0;
29     while(*q){
30         int id=*q-'a';
31         if(p->next[id]==NULL) return false;
32         else { q++;p=p->next[id]; }
33     }
34     return true; 
35 }
36 int main()
37 {
38     scanf("%d",&n);
39     root=create();// 先建造根节点 
40     for(int i=1;i<=n;i++){
41         scanf("%s",s);
42         insert(s);
43     }
44     scanf("%d",&m);
45     for(int i=1;i<=m;i++){
46         scanf("%s",s);
47         if(Judge(s)) printf("YES
");
48         else printf("NO
");
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/suishiguang/p/6290864.html