AC日记——字典 codevs 4189

时间:2023-03-08 18:50:06

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_[]; TreeNode *word[];
}; class TireTreeType {
private:
TreeNode *null,*root; inline void Insert_Tire(TreeNode *now,char str[])
{
int len=strlen(str);
for(int i=;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=;j<;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=;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=;i<;i++) null->word[i]=null;
root=new TreeNode;
for(int i=;i<;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[]; int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
scanf("%s",Cgets);
tree.Insert(Cgets);
}
scanf("%d",&m);
for(int i=;i<=m;i++)
{
scanf("%s",Cgets);
if(tree.Find(Cgets)) printf("YES\n");
else printf("NO\n");
}
return ;
}