#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=2*1e5+10;
int n,m,q,k,j;
struct Dictree//字典树
{
int cont;//单词出现次数
struct Dictree *tree[26];//26个子节点
}*a;//a为头结点是空的
void init()
{
a=new Dictree;
for(int i=0; i<26; ++i) //子节点置空
{
a->tree[i]=NULL;
}
}
void Insert(string str)//建树
{
int len,j;
Dictree *head=a;//head是头指针
len=str.size();
for(int i=0; i<len; ++i)
{
j=(int)(str[i]-'a');
if(head->tree[j]==NULL)//如果没有这个字母
{
head->tree[j]=new Dictree;
head=head->tree[j];
head->cont=1;//该节点值初始化
for(int k=0; k<26; k++)//子节点置空
head->tree[k]=NULL;
}
else
{
head=head->tree[j];
head->cont++;
}
}
}
int Find(string str)
{
int len=str.size();
Dictree *head=a;
for(int i=0; i<len; i++)//找字符串是否在树中出现过
{
j=(int)(str[i]-'a');
if(head->tree[j]!=NULL)
head=head->tree[j];
else//如果该字符没有则说明树中没有该字符串
return 0;
}
return head->cont;//找到后返回有多少个
}
int main()
{
init();
int n;
while(~scanf("%d",&n))
{
string str;
for(int i=0; i<n; i++)
{
cin>>str;
Insert(str);
}
int m;
cin>>m;
for(int i=0; i<m; i++)
{
cin>>str;
int sum=Find(str);
printf("%d\n",sum);
}
}
}
字典树
最新推荐文章于 2024-11-13 22:12:02 发布