字典树:又称前缀树
字典树入门:
字典树入门很简单:含义就像它的名字一样,我们利用前缀的思想,把信息按照前缀的思想挂树上,然后开出n个节点就🆗。
当把字典树建好,我们就进行查阅字典即可,入门字典树用二维数组存即可,是不是很简单
现在来看一道入门题目:传送门
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
//字典树:前缀树
const int maxn=2e6+5;
int tree[maxn][30];
int sum[maxn];
int tot;
void insert_str(char*str)
{
int len=strlen(str);
int root=0;
for(int i=0; i<len; i++)
{
int id=str[i]-'a';
if(!tree[root][id])
tree[root][id]=++tot;//记录节点数,tot代表节点总数
sum[tree[root][id]]++;//记录该前缀访问次数
root=tree[root][id];
}
}
int find_str(char *str)
{
int len=strlen(str);
int root=0,id;
for(int i=0; i<len; i++)
{
id=str[i]-'a';
if(!tree[root][id])
return 0;
root=tree[root][id];
}
return sum[root];
}
char str[maxn];
int main()
{
tot=0;
while(gets(str))
{
if(str[0]=='\0')
break;
insert_str(str);
}
while(~scanf("%s",str))
{
int ans=find_str(str);
printf("%d\n",ans);
}
}